重在UIPickerView的DataSourceDelegate和Delegate方法
效果图:
原代码如下:
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
#import "ViewController.h"
ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (nonatomic , strong) UIPickerView *pickerView;
@property (nonatomic , strong) NSArray *provinceArr;
@property (nonatomic , strong) NSDictionary *cityDic;
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self addPickerView];
}
-(void) addPickerView
{
[self.view addSubview:self.pickerView];
}
#pragma mark UIPivkerView DataSource Delegate
- (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == 0) {
return self.provinceArr.count;
}
else {
NSInteger proviceRow = [pickerView selectedRowInComponent:0];
NSString *provincName = self.provinceArr[proviceRow];
NSArray *cityArr = self.cityDic[provincName];
return cityArr.count;
}
}
#pragma mark UIPickerView Delegate
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if(component == 0){
[pickerView reloadComponent:1];
}
if(component == 1){
NSInteger rowOne = [pickerView selectedRowInComponent:0];
NSInteger rowTow = [pickerView selectedRowInComponent:1];
NSString *provinceName = self.provinceArr[rowOne];
NSArray *citys = self.cityDic[provinceName];
NSString *cityName = citys[rowTow];
NSLog(@"%@,%@",provinceName,cityName);
}
}
- (NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
if(component == 0){
return self.provinceArr[row];
}
if(component == 1){
NSInteger rowOne = [pickerView selectedRowInComponent:0];
NSString *provinceName = self.provinceArr[rowOne];
NSArray *citys = self.cityDic[provinceName];
NSString *cityName = citys[row];
return cityName;
}
return nil;
}
#pragma mark getter
- (UIPickerView *) pickerView
{
if (!_pickerView) {
_pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight-300, kScreenWidth, 300)];
_pickerView.dataSource = self;
_pickerView.delegate = self;
}
return _pickerView;
}
- (NSArray *) provinceArr
{
if (!_provinceArr) {
_provinceArr = @[@"北京", @"广西", @"广东",@"湖南"];
}
return _provinceArr;
}
- (NSDictionary *) cityDic
{
if (!_cityDic) {
_cityDic = @{
@"北京":@[@"朝阳区", @"东城区", @"西城区"],
@"广西":@[@"桂林市", @"南宁市"],
@"广东":@[@"惠州市", @"广州市", @"深圳市",@"东莞市"],
@"湖南":@[@"长沙市",@"湘潭市",@"株洲市",@"常德市"]
};
}
return _cityDic;
}
此Demo在于理解UIPickerView,对于要实现城市地区功能选择的小伙伴可建立一个.plist文件,在文件中添加省份和城市并一一对应。
后续将发表实现其功能的代码?。