省市选择
#import "ViewController.h"
#import "CZCityModel.h"
@interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (weak, nonatomic) IBOutlet UIPickerView *myPickerVeiw;
@property (weak, nonatomic) IBOutlet UILabel *lbProvince;
@property (weak, nonatomic) IBOutlet UILabel *lbCity;
//创建数据集合
@property(nonatomic,strong)NSArray *cityArray;
//临时集合
@property(nonatomic,strong)NSArray *tmpArray;
@end
@implementation ViewController
#pragma mark - 懒加载
- (NSArray *)cityArray
{
if (!_cityArray) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"cities.plist" ofType:nil];
NSArray *cities = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *tmpArray = [NSMutableArray array];
for (NSDictionary *dict in cities) {
CZCityModel *model = [CZCityModel cityWithDict:dict];
[tmpArray addObject:model];
}
_cityArray = tmpArray;
}
return _cityArray;
}
#pragma mark - pickerView的数据源方法
//返回多少列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
// return [self.cityArray[component] count];
//判断是不是第1列
if (component == 0) {//省
return self.cityArray.count;
}else{//市
//1.获取当前行 0列的行数
NSInteger currentRow = [pickerView selectedRowInComponent:0];
//2.是不是根据当前行 获取对应得城市列表
CZCityModel *model = self.cityArray[currentRow];
self.tmpArray = model.cities;
return model.cities.count;
}
}
#pragma mark - pickerView 的代理方法
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
// @(row) 几个意思??? NSNumber ;所有基本数据类型都是转换为NSNumber;
NSLog(@"titleForRow ----%@---",@(row));
//判断 当前的列
if(component == 0){//省
//省的名字
CZCityModel *model = self.cityArray[row];
return model.name;
}else{
//1.获取你选中的是当前的哪个的省份
// NSInteger currentRow = [pickerView selectedRowInComponent:0];
//
// //2.是不是根据选取的是哪个省 来获取对应的城市模型
// CZCityModel *model = self.cityArray[currentRow];
//
// //3.取出对应的城市
// return model.cities[row];
return self.tmpArray[row];
}
}
//停止的时候调用
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//1.刷新
if (component == 0) {//省列
//1.刷新城市
//全局
// [pickerView reloadAllComponents];
//局部
[pickerView reloadComponent:1];
//2. 自动选中 1列的第0行
[pickerView selectRow:0 inComponent:1 animated:YES];
}
//2.赋值 注意点: 你观察下 需要临时集合的帮助吗>??
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end