> IOS开发在线手册 > iOS开发-数据选择UIPickerView

UIPickerView开发一般选择区域或者分级数据的时候会使用到,类似于前端中用到树状结构,不过PC上一般都是从上到下的分级,使用UIPickView是从左到右实现,可以动态的设置UIPickView中中行列数据,将结果显示在文本输入框里,简单的定义一下数据源。通过声明协议捕获事件,展示结果,比较简单,进入正题.

页面布局

页面布局比较简单,一个UIPickerView,一个文本框:

iOS开发-数据选择UIPickerView

头文件中的声明,实现了UIPickerViewDelegate,UIPickerViewDataSource协议:

@interface ViewController : UIViewController <UIPickerViewDelegate,UIPickerViewDataSource>

@property (weak, nonatomic) IBOutlet UIPickerView *pickView;
@property (weak, nonatomic) IBOutlet UITextField *areaTextField;

@end

 Demo实现

定义存储数据的数组:

@interface ViewController ()
{
   NSArray *areaArr;
   NSMutableArray *teamArr;
}

初始化数据:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    areaArr=@[@"西南区",@"中央区",@"东南区",@"大西洋区",@"西北区",@"太平洋区"];
    teamArr=[[NSMutableArray alloc] init];
    [teamArr addObject:@[@"马刺",@"灰熊",@"小牛",@"火箭",@"鹈鹕"]];
    [teamArr addObject:@[@"活塞",@"步行者",@"骑士",@"公牛",@"雄鹿"]];
    [teamArr addObject:@[@"热火",@"魔术",@"老鹰",@"奇才",@"黄蜂"]];
    [teamArr addObject:@[@"凯尔特人",@"76人",@"尼克斯",@"篮网",@"猛龙"]];
    [teamArr addObject:@[@"森林狼",@"掘金",@"爵士",@"开拓者",@"雷霆"]];
    [teamArr addObject:@[@"国王",@"太阳",@"湖人",@"快船",@"勇士"]];
}

设置PickerView的列数:

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}

返回行数:

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    //判断列
    if (component==0) {
        return [areaArr count];
    }else{
        //判断0列中当前的行号
        NSInteger  currentRow=[pickerView selectedRowInComponent:0];
        return [teamArr[currentRow] count];
    }
}

 设置每行每列中的数据:

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (component==0) {
        //o列从区域数组中选择
        return areaArr[row];
    }else{
        //根据0列中选择的行号
        NSInteger  currentRow=[pickerView selectedRowInComponent:0];
        return teamArr[currentRow][row];
    }
}

 选择完成之后的事件:

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    [pickerView reloadComponent:1];
    NSInteger areaRow=[pickerView selectedRowInComponent:0];
    NSInteger teamRow=[pickerView selectedRowInComponent:1];
    [_areaTextField setText:[NSString stringWithFormat:@"%@-%@",areaArr[areaRow],teamArr[areaRow][teamRow]]];
    
}

 具体效果如下:

iOS开发-数据选择UIPickerView