第一篇寫了簡單的拾取器的展示和擷取,這一篇是雙輪拾取器的展示和擷取,内容大緻差不多,主要是雙輪之間的關聯~~~
代碼:
.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 == ){
return [self.pickerData1 objectAtIndex:row];
}else{
return [self.pickerData2 objectAtIndex:row];
}
}
//選擇某一行時觸發的事件,拾取器第二個輪的資料是和第一個輪關聯的
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
if(component == ){
NSString *selectedCol1 = [self.pickerData1 objectAtIndex:row];
NSArray *array = [self.data objectForKey:selectedCol1];
self.pickerData2 = array;
[self.pv reloadComponent:];
}
}
//傳回兩個輪的資料數量
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
if(component == ){
return [self.pickerData1 count];
}else{
return [self.pickerData2 count];
}
}
//傳回拾取器的輪數
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return ;
}
//點選按鈕顯示目前拾取器的資料
-(IBAction)onClick:(id)sender{
//第一個輪的行數
NSInteger row1 = [_pv selectedRowInComponent:];
//第二個輪的行數
NSInteger row2 = [_pv selectedRowInComponent:];
//第一個輪的值
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: ];
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和新改的名稱連接配接起來~~~
每次都會遇到問題,解決問題的過程就是我們成長的過程,加油~~