首先建立工程,然後再stroyboard拖入UIPicker,為在程式中通路該控件,需要将該控件綁定到picker IBOutlet屬性
然後實作兩個協定,這兩個協定是必須存在的。代碼如下
#import "ViewController.h"
@interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property (strong, nonatomic) IBOutlet UIPickerView *picker;
@end
@implementation ViewController
{
NSDictionary *books;
NSArray *authors;
//selectedAuthor儲存目前選中的作者
NSString *selectAuthor;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//建立并初始化NSDictionary對象
books = [NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithObjects:@"飛鳥集",@"祭壇急了", nil],@"泰戈爾",
[NSArray arrayWithObjects:@"醒世恒言",@"喻世明言",@"警世通言", nil],@"馮夢龍",
[NSArray arrayWithObjects:@"ios講義",@"andros講義",@"java講義",@"xml講義", nil],@"李剛",nil];
//使用author 儲存books所有key所組成的NSArray排序後的結果
authors = [[books allKeys] sortedArrayUsingSelector:@selector(compare:)];
//使用預設選中的作者authors中的第一個元素
selectAuthor = [authors objectAtIndex:0];
self.picker.delegate = self;
self.picker.dataSource = self;
}
//該方法傳回控件該控件包含多少列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
//該方法傳回值決定該控件的制定列包含多少個清單項
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
if (component == 0) {
return authors.count;
}
return [[books objectForKey:selectAuthor] count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
//若果是第一列,則傳回authors中的元素的個數
//即authors有多少個元素,那麼第一列就包含多少個清單項
if (component == 0) {
return [authors objectAtIndex:row];
}
//否則其他列傳回的個數是books中的鍵值對中值對應的數組地元素的個數
return [[books objectForKey:selectAuthor] objectAtIndex:row];
}
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
//如果是第一列,則寬度是90
if (component == 0 ) {
return 90;
}
return 210;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if (component == 0) {
//改變選中的作者
selectAuthor = [authors objectAtIndex:row];
}
//控制重寫加載第二個清單,根據選中的作者來加載第二個清單項
[self.picker reloadComponent:1];
}
@end
運用下面該方法可以任意定制自己的的選擇器視圖
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
view = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"引導頁二640-1136"]];
return view;
}
如圖所示