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