关于UIPickerView

UIPickerView是一个选择器控件,它比UIDatePicker更加通用,它可以生成单列的选择器,也可生成多列的选择器,而且开发者完全可以自定义选择项的外观,因此用法非常灵活。UIPickerView直接继承了UIView,没有继承UIControl,因此,它不能像UIControl那样绑定事件处理方法,UIPickerView的事件处理由其委托对象完成。

UIDatePicker控件只是负责该控件的通用行为,而该控件包含多少列,各列包含多少个列表项则由UIPickerViewDataSource对象负责。开发者必须为UIPickerView设置UIPickerViewDataSource对象,并实现如下两个方法。

  • - numberOfComponentsInPickerView: 该UIPickerView将通过该方法来判断应该包含多少列。
  • - pickerView:numberOfRowsInComponent: 该UIPickerView将通过该方法判断指定列应该包含多少个列表项。

如果程序需要控制UIPickerView中各列的宽度,以及各列中列表项的大小和外观,或程序需要为UIPickerView的选中事件提供响应,都需要为UIPickerView设置UIPickerViewDelegate委托对象,并根据需要实现该委托对象中的如下方法。

  • - pickerView:rowHeightForComponent: 该方法返回的CGFloat值将作为该UIPickerView控件中指定列中列表项的高度。
  • - pickerView:widthForComponent: 该方法返回的CGFloat值将作为该UIPickerView控件中指定列的宽度。
  • - pickerView:titleForRow:forComponent: 该方法返回的NSString值将作为该UIPickerView控件中指定列的列表项的文本标题。
  • - pickerView:viewForRow:forComponent:reusingView: 该方法返回的UIView控件将直接作为该UIPickerView控件中指定列的指定列表项。
  • - pickerView:didSelectRow:inComponent: 当用户单击选中该UIPickerView控件的指定列的指定列表项时将会激发该方法。
// 监听轮子的滚动
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == kStateComponent) {
        NSString * selectedState = self.firstArr[row];
        self.secondArr = self.dataDic[selectedState];
       
       // !!! 更新第二个轮子的数据
        [_pick reloadComponent:kZipcomponent];
        [_pick selectRow:0 inComponent:kZipcomponent animated:YES];
    }
    
    // 获取UIPickerView的不同的component选中的那行
    NSInteger stateRow = [self.pick selectedRowInComponent:kStateComponent];
    NSInteger zipRow = [self.pick selectedRowInComponent:kZipcomponent];
    
    NSString *state = self.firstArr[stateRow];
    NSString *zip = self.secondArr[zipRow];
    
    NSString * title = [[NSString alloc] initWithFormat:@"You selected zip code %@",zip];
    NSString * message = [[NSString alloc] initWithFormat:@"%@ is in %@",zip,state];
    
    //官方解释:UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is also deprecated.) To create and manage alerts in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert. (主要是说UIAlertView在iOS 8中被废弃了,取而代之的是UIAlertController)

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:nil];
}
关于UIPickerView_第1张图片

你可能感兴趣的:(关于UIPickerView)