UIPickerView爲用戶提供了選擇器功能,使用戶以更好的體驗方式實現數據的選擇,如圖:spa
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
實現部分:code
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 }