UIPickerView为用户提供了选择器功能,使用户以更好的体验方式实现数据的选择,如图:
UIPickerView控件的使用方法:(创建好根视图:MainViewController)
#import <UIKit/UIKit.h>
@interface MainViewController : UIViewController<UIPickerViewDelegate>
{
UIPickerView *pickerView;
UILabel *contentview;
NSArray *content; // 星座;
}
@end
实现部分:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
-(void)loadView
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
self.view = view;
view.backgroundColor = [UIColor yellowColor];
[view release];
// 初始化数据, 这些数据将显示在picker中
content = [[NSArray alloc] initWithObjects:@"水瓶座", @"双鱼座", @"白羊座 ", @"金牛座", @"双子座", @"巨蟹座", @"狮子座", @"处女座", @"天秤座", @"天蝎座", @"射手座", @"白羊座",nil];
// 设置选择器
pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 150, 320, 216)];
// 设置代理
pickerView.delegate = self;
pickerView.showsSelectionIndicator = YES;
[self.view addSubview:pickerView];
contentview = [[UILabel alloc] initWithFrame:CGRectMake(80, 80, 100, 40)];
contentview.backgroundColor = [UIColor clearColor];
[self.view addSubview:contentview];
}
#pragma mark--处理方法
// 返回显示的数列
- (NSInteger)numberOfRowsInComponent:(NSInteger)component
{
return 1;
}
// 返回当前列显示的行数
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [content count];
}
// 设置当前的内容,如果行没有显示则自动释放
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [content objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// NSString *result = [pickerView pickView:pickerView titleForRow:row forComponent:component];
NSString *result = nil;
result = [content objectAtIndex:row];
NSLog(@"result:%@", result);
contentview.text = result;
[result release];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}