uipicker对省市的遍历
Posted 清浅晨曦
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了uipicker对省市的遍历相关的知识,希望对你有一定的参考价值。
1、首先,对UIPickerView绑定Delegate和DataSource到相应的ViewController。此处不再赘述。可以用代码或者Interface界面设置。
2、首先实现数据的初始化。
(1)在.h文件中定义如下变量。其中provinces_cities.plist请见附件。
- @interface IkrboyViewController : UIViewController{
- NSDictionary *dict;//用于存储省份-城市的数据
- NSArray *provinceArray;//省份的数组
- NSArray *cityArray;//城市的数组,在接下来的代码中会有根据省份的选择进行数据更新的操作
- }
(2)在.m的viewDidLoad方法中加上初始化数据的处理。具体处理在initPicker方法
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- [self initPicker];
- }
- //初始化PickerView使用的数据源
- -(void)initPicker{
- NSBundle *bundle = [NSBundle mainBundle];
- NSString *plistPath = [bundle pathForResource:@"provinces_cities" ofType:@"plist"];
- dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
- provinceArray = [dict allKeys];
- NSInteger selectedProvinceIndex = [self.pickerView selectedRowInComponent:0];
- NSString *seletedProvince = [provinceArray objectAtIndex:selectedProvinceIndex];
- cityArray = [dict objectForKey:seletedProvince];
- NSLog(@"%d",[provinceArray count]);
- }
3、将数据绑定到UIPickerView
- //以下3个方法实现PickerView的数据初始化
- //确定picker的轮子个数
- - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
- return 2;
- }
- //确定picker的每个轮子的item数
- - (NSInteger)pickerView:(UIPickerView *)pickerView
- numberOfRowsInComponent:(NSInteger)component {
- if (component == 0) {//省份个数
- return [provinceArray count];
- } else {//市的个数
- return [cityArray count];
- }
- }
- //确定每个轮子的每一项显示什么内容
- #pragma mark 实现协议UIPickerViewDelegate方法
- -(NSString *)pickerView:(UIPickerView *)pickerView
- titleForRow:(NSInteger)row forComponent:(NSInteger)component {
- if (component == 0) {//选择省份名
- return [provinceArray objectAtIndex:row];
- } else {//选择市名
- return [cityArray objectAtIndex:row];
- }
- }
4.随时监听UIPickerView的滚动。
- //监听轮子的移动
- - (void)pickerView:(UIPickerView *)pickerView
- didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
- if (component == 0) {
- NSString *seletedProvince = [provinceArray objectAtIndex:row];
- cityArray = [dict objectForKey:seletedProvince];
- //重点!更新第二个轮子的数据
- [self.pickerView reloadComponent:1];
- NSInteger selectedCityIndex = [self.pickerView selectedRowInComponent:1];
- NSString *seletedCity = [cityArray objectAtIndex:selectedCityIndex];
- NSString *msg = [NSString stringWithFormat:@"province=%@,city=%@", seletedProvince,seletedCity];
- NSLog(@"%@",msg);
- }
- else {
- NSInteger selectedProvinceIndex = [self.pickerView selectedRowInComponent:0];
- NSString *seletedProvince = [provinceArray objectAtIndex:selectedProvinceIndex];
- NSString *seletedCity = [cityArray objectAtIndex:row];
- NSString *msg = [NSString stringWithFormat:@"province=%@,city=%@", seletedProvince,seletedCity];
- NSLog(@"%@",msg);
- }
- }
以上是关于uipicker对省市的遍历的主要内容,如果未能解决你的问题,请参考以下文章