Problem: You want to select data from a list in the program.
The picker view can display a series of values to users and allow users to select one of them. The time selection in the iPhone clock program is a good example.
. H file:
#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UIPickerViewDataSource,UIPickerViewDelegate>@property(nonatomic,strong)UIPickerView *myPicker;@end
. M:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = [UIColor whiteColor]; self.myPicker = [[UIPickerView alloc]init]; self.myPicker.center = self.view.center; self.myPicker.delegate = self;//设置代理 self.myPicker.showsSelectionIndicator = YES; [self.view addSubview:self.myPicker]; //此时pickerView没有数据,效果不好. ///为选择器添加数据:首先给 picker view 指定一个 data source,然后确保 view controller 遵循相关的协议。UIPickerView 的 data source 实例必须遵循 UIPickerViewDataSource 协议。}//UIPickerViewDataSource @required协议方法的实现-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{ //这个方法主要是用来为你的选择器添加组件的,如果你需要多个组件,你可以在这个里面进行添加. return 1;}-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{ //顾名思义,这个方法表示你的一个组件中有多少个选项。 return 10;}//UIPickerViewDelegate 协议方法-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{ NSString *result = nil; if ([pickerView isEqual:_myPicker]) { result = [NSString stringWithFormat:@"Row%ld",row+1]; } return result;}
:
We cannot detect the items actually selected by the user and obtain the data selected by the user. We can call uipickerviewselectedrowincomponent: method. If you need to modify the value in the picker view when the program is running, reload the relevant data from data source and delegate. You can use the reloadallcomponent method to forcibly Reload all data, or use the reloadcomponent: Method to load the data of the specified component.
Ui: Use uipickerview to select data