//必须实现两个协议
//数据源协议必须实现的两个方法
//选取器的输出借口singlePicker,并在故事版中选择该选取器将dataSource和delegate拖入视图控制器与之关联
//@property (weak, nonatomic) IBOutlet UIPickerView *singlePicker;
//characterNames是自己定义的属性数组,用于往选取器中添加显示数据
//@property (strong, nonatomic) NSArray *characterNames;
//选取器显示几个滚轮,返回1,显示1个
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return ;
} //选取器滚轮包含多少行,返回数组对象中的数量
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component { return [self.characterNames count];
} //委托协议,实现可选方法
//使用row参数作为索引,返回数组中相应的元素
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component { return self.characterNames[row];
} //点击按钮触发事件,弹出警告框显示在选取器中选择的内容
- (IBAction)buttonPressed:(id)sender {
//选取器组成部分0代表第一个选取器,1则代表第二个选取器,以此类推,赋值给一个整型对象 row
NSInteger row = [self.singlePicker selectedRowInComponent:];
//获取数组中的内容并赋值给字符串对象selected
NSString *selected = self.characterNames[row];
NSString *title = [NSString stringWithFormat:@"You selected %@",selected]; UIAlertController *singleAlert = [UIAlertController alertControllerWithTitle:title message:@"thank you for choosing" preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *singleAction = [UIAlertAction actionWithTitle:@"Yes I did" style:UIAlertActionStyleDefault handler:nil]; [singleAlert addAction:singleAction]; [self presentViewController:singleAlert animated:YES completion:nil];