要想使用UIPickerView,必须要知道UIPickerView的协议UIPickerViewDataSource,UIPickerViewDelegate,协议中主要的方法如下:
1、- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;//一共有多少列
2、- (NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;//第component列第row行显示什么。
3、- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component;//选中了第component列的第row行
4、- (void)reloadComponent:(NSInteger)component;//重新加载第component列数据
下面通过一个例子详细说明下UIPickerView的使用,例子是开发中常用的级联操作,选择第一列的省,第二列加载相应的市。
#pragma UIPickerViewDataSource 代理方法
// returns the number of 'columns' to display. 一共有多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
// returns the # of rows in each component..第几列显示多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == 0) {
// 第一列有多少个省份
return _provinces.count;
} else {
// 1.获得选中了哪一个省
int pIndex = [pickerView selectedRowInComponent:0];
// 2.取出省份模型
FCProvince *p = _provinces[pIndex];
// 3.返回当前省份城市的个数
return p.cities.count;
}
}
//第n列第n行显示什么
- (NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if (component == 0) { // 省
FCProvince *pro = self.provinces[row];
return pro.name;
} else { // 市
// 1.获得选中了哪一个省
int pIndex = [pickerView selectedRowInComponent:0];
// 2.取出省份模型
FCProvince *p = _provinces[pIndex];
// 3.返回对应行的城市名称
return p.cities[row]; }
}
/**
* 选中了第component列的第row行
*/
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
// 刷新第1列的数据(重新刷新数据,重新调用数据源和代理的相应方法获得数据)
[pickerView reloadComponent:1];
// 选中第1列的第0行
[pickerView selectRow:0 inComponent:1 animated:YES];
}
// 1.获得选中了哪一个省
int pIndex = [pickerView selectedRowInComponent:0];
FCProvince *p = _provinces[pIndex];
self.lblProvince.text = p.name;
int cIndex = [pickerView selectedRowInComponent:1];
self.lblCity.text = p.cities[cIndex];
}