本節(jié)學(xué)習(xí)內(nèi)容:
1.UIPickerView的概念
2.UIPickerView的協(xié)義方法
3.UIPickerView的應(yīng)用
UIPickerView的屬性
dataSource:數(shù)據(jù)代理對象
numberOfComponentsLnPickerView:獲得分組個(gè)數(shù)協(xié)義
numberOfRowsInComponent:獲得行數(shù)協(xié)義
titleForRow:獲得元素文字協(xié)義
rowHeightForCimponent:設(shè)置行高f協(xié)義
viewForRow:獲取視圖對象元素協(xié)義
[ViewController.h】
#import<UIKit/UIKit.h>
@interface
//添加UIPickerViewDelegate:普通協(xié)義代理砍聊,處理視圖選取等普通事件協(xié)義功能,,UIPickerViewDataSource:數(shù)據(jù)協(xié)義代理,處理獲取數(shù)據(jù)的代理協(xié)義函數(shù)
ViewController:UIViewController<UIPickerViewDelegate,UIPickerViewDataSource>
【ViewController.m】
#import"ViewController.h"
@interface ViewController()
@end
@implementation ViewController
-(void)viewdidLoad{
[super viewDidLoad];
//創(chuàng)建選擇視圖對象荒给,顯示多組數(shù)據(jù)和多個(gè)元素以供選擇魁瞪,例如選擇日期济舆,時(shí)間涩嚣,日歷效果赃梧,地區(qū)地址等功能
UIPickerView* ickerView=[[UIPickerView alloc]init];
pickerView.frame=CGRectMake[10,100,300,200);
//設(shè)置普通代理對象為當(dāng)前的視圖控器
pickerView.delegate=self;
//設(shè)置數(shù)據(jù)代理對象為當(dāng)前視圖控制器
pickerView.dataSource=self;
[self.view addSubview:pickerView];
}
//實(shí)現(xiàn)獲取組數(shù)的協(xié)議函數(shù)固以,返回值為選擇視圖的組數(shù)墩虹,整形類型
-(NSInteger)numberOfCpnponentsInPickerView:(UIOickerView *)pickerView{
returen 3;
}
//實(shí)現(xiàn)每組元素的個(gè)數(shù),每組無素有多少行憨琳,參數(shù)1:調(diào)用此協(xié)義的選擇視圖本身诫钓,參數(shù)2:第幾組的無素個(gè)數(shù)
-(NSInteger)pickerView:(UIPickerView *)pickerView numberofRowsInComponent:(NSInteger)component{
//第一組返回5個(gè)
if(component==0){
return 5;
}
//第二組返回10個(gè)
else if(component==1){
return 10;
}
//第二組返回20個(gè)
else if(component==2){
return 20;
}
//每組10行
return 10;
}
//顯示每個(gè)元素的內(nèi)容,參數(shù)1:調(diào)用此協(xié)義的選擇視圖本身篙螟,參數(shù)2:行數(shù)菌湃,參數(shù)3:組數(shù)
-(NSString *)pickerView(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
NSString* str=[NSString stringWithformat:@"%d組%d行",component+1,row+1];
return str;
}
//設(shè)置每行元素的高度
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
return 80;
}
//可以將自定義的視圖顯示到屏幕上
-(UIView*)pickerView:(UIPickerview *)pickerView viewForRow:(NSInteger)row forcomPonent:(NSInteger)component reusingView:(UIView *)view{
UIImage* image=[UIImage imageNamed:[NSString stringWithFormat:@"%ld.png",(row)%7+1]];
UIImageView* iView=[[UIImageView alloc]initWithImage:image];
//設(shè)置圖片顯示大小
iView.frame=CGRectMake(0,0,40,40);
return iView;
}