首页 > 代码库 > UIPickerView实例

UIPickerView实例

+ (id)cityPicker
{
   
return [[NSBundlemainBundle]loadNibNamed:@"MJCityPicker"owner:niloptions:nil][0];
}

#pragma mark任何对象从xib中创建完毕的时候都会调用一次
- (void)awakeFromNib
{
   
NSArray *array = [NSArrayarrayWithContentsOfFile:[[NSBundlemainBundle]pathForResource:@"cities.plist"ofType:nil]];
   
   
_provinces = [NSMutableArrayarray];
   
for (NSDictionary*dict in array) {
       
MJProvince *p = [MJProvinceprovinceWithDict:dict];
        [
_provincesaddObject:p];
    }
}

#pragma mark - UIPickerView数据源方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView*)pickerView
{
   
return 2;
}

#pragma markcomponent列有多少行数据
- (NSInteger)pickerView:(UIPickerView*)pickerView numberOfRowsInComponent:(NSInteger)component
{
   
if (component ==0) {//多少个省份
       
return _provinces.count;
    }
else { // 当前选中省份的行数(城市个数)
       
// 1.获得选中了哪一个省
       
int pIndex = [pickerViewselectedRowInComponent:0];
       
       
// 2.取出省份模型
       
MJProvince *p =_provinces[pIndex];
       
       
// 3.返回当前省份城市的个数
       
return p.cities.count;
    }
}

#pragma mark - UIPickerView代理方法
- (NSString*)pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
   
if (component ==0) {//显示哪个省份
       
// 1.取出省份模型
       
MJProvince *p =_provinces[row];
       
       
// 2.取出省份名称
       
return p.name;
    }
else { // 显示哪个城市
       
// 1.获得选中了哪一个省
       
int pIndex = [pickerViewselectedRowInComponent:0];
       
       
// 2.取出省份模型
       
MJProvince *p =_provinces[pIndex];
       
       
// 3.返回对应行的城市名称
       
return p.cities[row];
    }
}

#pragma mark监听选中了某一列的某一行
- (void)pickerView:(UIPickerView*)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
   
if (component ==0) {//改变了省份
       
// 刷新第1列的数据(重新刷新数据,重新调用数据源和代理的相应方法获得数据)
        [pickerView
reloadComponent:1];
       
       
// 选中第1列的第0
        [pickerView
selectRow:0inComponent:1animated:YES];
    }
   
   
// 更改文字
   
// 1.获得选中的省份名称
   
int pIndex =  [pickerViewselectedRowInComponent:0];
   
MJProvince *p =_provinces[pIndex];
   
   
// 2.获得选中的城市位置
   
int cIndex = [pickerViewselectedRowInComponent:1];
   
   
// 3.通知代理
   
if ([_delegaterespondsToSelector:@selector(cityPicker:citySelectWithProvince:city:)]) {
        [
_delegatecityPicker:selfcitySelectWithProvince:p.namecity:p.cities[cIndex]];
    }
}

#pragma mark 代理协议
@protocolMJCityPickerDelegate <NSObject>

@optional
- (
void)cityPicker:(MJCityPicker*)cityPicker citySelectWithProvince:(NSString*)province city:(NSString*)city;

@end

注意:
由于UIPickerView继承自UIView,里面有数据源和代理,因此UIPickerView展示数据通过数据源,监听事件通过代理。

UIPickerView实例