UIKit框架-高级控件:9.UIPickerView简易城市地区选择器
在前面我们知道了UIPickerView的使用方法, 也结合过其他UI控件一起来使用, 现在让再来一个演练.
1.在.h文件中设置代理方法
@interface ViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate> @end
2.在.m文件里设置全局变量
@interface ViewController () { NSArray *_province; NSMutableDictionary *_city; }
PS: 这里设置全局变量是为了方便我们存储数据, 非必要时不要乱定义.
3.实例化UIPickerView
- (void)myPickerView { UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 200, self.view.frame.size.width, 268)]; [pickerView setBackgroundColor:[UIColor grayColor]]; [pickerView setDataSource:self]; [pickerView setDelegate:self]; [pickerView setShowsSelectionIndicator:YES]; [self loadPickerData]; [self.view addSubview:pickerView]; }
4.设置城市省份数据
- (void)loadPickerData { _province = @[@"北京", @"广西", @"广东"]; _city = [NSMutableDictionary dictionary]; NSArray *city1 = @[@"朝阳区", @"东城区", @"西城区"]; [_city setValue:city1 forKey:@"北京"]; NSArray *city2 = @[@"桂林市", @"南宁市"]; [_city setValue:city2 forKey:@"广西"]; NSArray *city3 = @[@"惠州市", @"广州市", @"深圳市", @"东莞市"]; [_city setValue:city3 forKey:@"广东"]; }
5.设置UIPickerView的数据源方法
#pragma mark 设置列 - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView { return 2; } #pragma mark 设置行 - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component { if (component == 0) { return _province.count; } else { NSInteger rowProvince = [pickerView selectedRowInComponent:0]; NSString *provinceName = _province[rowProvince]; NSArray *citys = _city[provinceName]; return citys.count; } }
6.设置UIPickerView的代理方法
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { if (component == 0) { return _province[row]; } else { NSInteger rowProvince = [pickerView selectedRowInComponent:0]; NSString *provinceName = _province[rowProvince]; NSArray *citys = _city[provinceName]; return citys[row]; } }
7.UIPickerView刷新数据的方法
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { [pickerView reloadComponent:1]; NSInteger rowOne = [pickerView selectedRowInComponent:0]; NSInteger rowTow = [pickerView selectedRowInComponent:1]; NSString *provinceName = _province[rowOne]; NSArray *citys = _city[provinceName]; NSLog(@"%@~%@", _province[rowOne], citys[rowTow]); }
PS: 如果不添加该方法, 那么在切换省份的时候就不会更改市区.
最终效果图:
好了, 这次我们就讲到这里, 下次我们继续~~~