UIPickerView 创建中国地区显示 省份 市

第一步初始化 UIPickerView *pickerview; //城市滚动表

NSDictionary *dict; //用于存储省份-城市的数据

NSArray *provinceArray; //省份的数组

NSArray *cityArray; //城市的数组

第二步需要引入代理 UIPickerViewDataSource,UIPickerViewDelegate,

第三步把拥有的地区从文件取出来 要文件留言NSBundle *bundle = [NSBundle mainBundle];

NSString *plistPath = [bundle pathForResource:@"city" ofType:@"plist"];

provinceArray=[NSArray arrayWithContentsOfFile:plistPath];

NSLog(@"-----------%@",provinceArray);

cityArray = [[provinceArray objectAtIndex:0] objectForKey:@"cities"];

NSLog(@"+ + + + + %@",cityArray);

pickerview = [[UIPickerView alloc]initWithFrame:CGRectMake(50, 200, 250, 100)];

pickerview.delegate =self;

pickerview.dataSource =self;

[self.View addSubview:pickerview];

//用来显示取出的地区名字

placelabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 55, Kwidth, 25)];

placelabel.backgroundColor = [UIColor redColor];

placelabel.textAlignment = NSTextAlignmentLeft;

[self.View addSubview:placelabel];

下面的为代理方法

//*个数

- (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 {

switch (component) {

case 0:

return [[provinceArray objectAtIndex:row] objectForKey:@"state"];

break;

case 1:

return [cityArray objectAtIndex:row];

break;

default:

return @"";

break;

}

}

//监听*的移动

- (void)pickerView:(UIPickerView *)pickerView

didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

// NSLog(@"1111111111111 %d",cityArray.count);

// NSLog(@"1111111111111 %d",provinceArray.count);

//

switch (component) {

case 0:

cityArray = [[provinceArray objectAtIndex:row] objectForKey:@"cities"];

[pickerView selectRow:0 inComponent:1 animated:YES];

[pickerView reloadComponent:1];

NSLog(@"%@",[[provinceArray objectAtIndex:row] objectForKey:@"state"]);

NSLog(@"%@",[cityArray objectAtIndex:0]);

pla = [[NSString alloc]initWithFormat:@"%@",[[provinceArray objectAtIndex:row] objectForKey:@"state"]];

placelabel.text = [NSString stringWithFormat:@"%@-%@",[[provinceArray objectAtIndex:row] objectForKey:@"state"],[cityArray objectAtIndex:0]];

break;

case 1:

NSLog(@"%@",[cityArray objectAtIndex:row]);

placelabel.text = [NSString stringWithFormat:@"%@-%@",pla,[cityArray objectAtIndex:row]];

break;

default:

break;

}

}

上一篇:QQ揭秘:如何实现托盘闪动消息提醒?【低调赠送:QQ高仿版GG 4.1 最新源码】


下一篇:【设计模式 - 10】之外观模式(Facade)