iOS UI 基础

关于UIPickerView

2016-03-02  本文已影响216人  诺馨

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

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

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

// 监听轮子的滚动
- (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];
}
上一篇下一篇

猜你喜欢

热点阅读