首先添加UIPickerViewDelegate代理
在.h文件中添加
@interface ViewController : UIViewController<UIPickerViewDelegate,UIPickerViewDataSource>
@property (weak, nonatomic) IBOutlet UIPickerView *pickerview;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (nonatomic,strong) NSDictionary *pickerData;
@property (nonatomic,strong) NSArray *proviencesData;
@property (nonatomic,strong) NSArray *cityData;
@end
//
// ViewController.m
// test_04
//
// Created by frola on 2017/10/10.
// Copyright © 2017年 frola. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 读取plist文件中的数据
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"proven" ofType:@"plist"];
NSDictionary *dic = [[NSDictionary alloc]initWithContentsOfFile:path];
self.pickerData = dic;
self.proviencesData = [_pickerData allKeys];
NSString *selectProvience = [self.proviencesData objectAtIndex:0];
self.cityData = [self.pickerData objectForKey:selectProvience];
self.pickerview.dataSource = self;
self.pickerview.delegate = self;
}
- (IBAction)getText:(id)sender {
NSInteger row1 = [self.pickerview selectedRowInComponent:0];
NSInteger row2 = [self.pickerview selectedRowInComponent:1];
NSString *select1 = [self.proviencesData objectAtIndex:row1];
NSString *select2 = [self.cityData objectAtIndex:row2];
NSString *title = [NSString stringWithFormat:@"%@||%@",select1,select2];
_label.text = title;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 2;
}
- (NSInteger)pickerView:(nonnull UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
if (component == 0) {
return _proviencesData.count;
}else{
return _cityData.count;
}
return 0;
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if (component==0) {
return [self.proviencesData objectAtIndex:row];
}else{
return [self.cityData objectAtIndex:row];
}
return @"";
}
//切换省份后,城市刷新
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
if (component == 0) {
NSString *selectProvience = [self.proviencesData objectAtIndex:row];
self.cityData = [self.pickerData objectForKey:selectProvience];
[self.pickerview reloadComponent:1];
}
}
@end
省份数据添加在plist文件中