第一篇写了简单的拾取器的展示和获取,这一篇是双轮拾取器的展示和获取,内容大致差不多,主要是双轮之间的联动~~~
代码:
.h的代码
#import <UIKit/UIKit.h>
//<UIPickerViewDelegate, UIPickerViewDataSource>是事件代理,和数据源代理,在.m文件中实现方法添加事件和数据源
@interface ViewController : UIViewController<UIPickerViewDataSource,UIPickerViewDelegate>
//数据字典
@property (nonatomic, strong) NSDictionary *data;
//拾取器第一个轮的数据数组
@property (nonatomic, strong) NSArray *pickerData1;
//拾取器第二个轮的数据数组
@property (nonatomic, strong) NSArray *pickerData2;
//拾取器声明
@property (strong, nonatomic) IBOutlet UIPickerView *pv;
//显示拾取器的标签
@property (strong, nonatomic) IBOutlet UILabel *lable;
//点击按钮显示拾取器方法声明
-(IBAction)onClick:(id)sender;
@end
.m文件的代码
//实现协议UIPickerViewDelegate方法
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
if(component == 0){
return [self.pickerData1 objectAtIndex:row];
}else{
return [self.pickerData2 objectAtIndex:row];
}
}
//选择某一行时触发的事件,拾取器第二个轮的数据是和第一个轮关联的
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
if(component == 0){
NSString *selectedCol1 = [self.pickerData1 objectAtIndex:row];
NSArray *array = [self.data objectForKey:selectedCol1];
self.pickerData2 = array;
[self.pv reloadComponent:1];
}
}
//返回两个轮的数据数量
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
if(component == 0){
return [self.pickerData1 count];
}else{
return [self.pickerData2 count];
}
}
//返回拾取器的轮数
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 2;
}
//点击按钮显示当前拾取器的数据
-(IBAction)onClick:(id)sender{
//第一个轮的行数
NSInteger row1 = [_pv selectedRowInComponent:0];
//第二个轮的行数
NSInteger row2 = [_pv selectedRowInComponent:1];
//第一个轮的值
NSString * mys1 = [self.pickerData1 objectAtIndex:row1];
//第二个轮的值
NSString *mys2 = [self.pickerData2 objectAtIndex:row2];
NSString *str = @"";
//标签显示两个轮的拼接字符串
_lable.text = [str stringByAppendingString:[NSString stringWithFormat:@"%@,%@",mys1,mys2]];
}
//初始化
- (void)viewDidLoad {
[super viewDidLoad];
//用NSBundle读取资源文件
NSBundle *bundle = [NSBundle mainBundle];
//statedictionary是资源文件的名字
NSString *plistPath = [bundle pathForResource:@"statedictionary" ofType:@"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.data = dict;
NSArray *col1 = [self.data allKeys];
//排序
NSArray *sorted = [col1 sortedArrayUsingSelector:@selector(compare:)];
self.pickerData1 = sorted;
//初始化第二个轮的数据
NSString *selectedCol1 = [self.pickerData1 objectAtIndex: 0];
NSArray *col2 = [self.data objectForKey:selectedCol1];
self.pickerData2 = col2;
// Do any additional setup after loading the view, typically from a nib.
}
资源plist文件为:
nib文件
遇到的问题:
中途我改过一次UIPickerView的名称,然后报错了,233~
找了半天,发现改了名称之后要在nib文件中重新拖拽,让File’s Owner和新改的名称连接起来~~~
每次都会遇到问题,解决问题的过程就是我们成长的过程,加油~~