UIPickerView为用户提供了选择器功能,使用户以更好的体验方式实现数据的选择,如图:
UIPickerView控件的使用方法:(创建好根视图:MainViewController)
1 #import <UIKit/UIKit.h> 2 3 @interface MainViewController : UIViewController<UIPickerViewDelegate> 4 { 5 UIPickerView *pickerView; 6 UILabel *contentview; 7 NSArray *content; // 星座; 8 } 9 10 @end
实现部分:
1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 // Do any additional setup after loading the view. 5 } 6 -(void)loadView 7 { 8 UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)]; 9 self.view = view; 10 view.backgroundColor = [UIColor yellowColor]; 11 [view release]; 12 // 初始化数据, 这些数据将显示在picker中 13 content = [[NSArray alloc] initWithObjects:@"水瓶座", @"双鱼座", @"白羊座 ", @"金牛座", @"双子座", @"巨蟹座", @"狮子座", @"处女座", @"天秤座", @"天蝎座", @"射手座", @"白羊座",nil]; 14 // 设置选择器 15 pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 150, 320, 216)]; 16 // 设置代理 17 pickerView.delegate = self; 18 pickerView.showsSelectionIndicator = YES; 19 [self.view addSubview:pickerView]; 20 contentview = [[UILabel alloc] initWithFrame:CGRectMake(80, 80, 100, 40)]; 21 contentview.backgroundColor = [UIColor clearColor]; 22 [self.view addSubview:contentview]; 23 } 24 #pragma mark--处理方法 25 // 返回显示的数列 26 - (NSInteger)numberOfRowsInComponent:(NSInteger)component 27 { 28 return 1; 29 } 30 // 返回当前列显示的行数 31 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component 32 { 33 return [content count]; 34 } 35 // 设置当前的内容,如果行没有显示则自动释放 36 - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component 37 { 38 return [content objectAtIndex:row]; 39 } 40 - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component 41 { 42 // NSString *result = [pickerView pickView:pickerView titleForRow:row forComponent:component]; 43 44 NSString *result = nil; 45 result = [content objectAtIndex:row]; 46 NSLog(@"result:%@", result); 47 contentview.text = result; 48 [result release]; 49 } 50 - (void)didReceiveMemoryWarning 51 { 52 [super didReceiveMemoryWarning]; 53 // Dispose of any resources that can be recreated. 54 }