UIPickerView繼承自UIView,所以不能像UIControl樣綁定事件處理方法,所以UIPickerView的事件處理由其委托對象完成。
@interface ViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
_myPicker = [[UIPickerView alloc] init];
//設置高亮顯示
_myPicker.showsSelectionIndicator = YES;
//數據源
_myPicker.dataSource = self;
//代理
_myPicker.delegate = self;
//放在正中間
_myPicker.center = self.view.center;
//顯示的時候是第幾個,索引是從0開始的,顯示第5個
[_myPicker selectRow:4 inComponent:0 animated:YES];
//第二列,也是第5個
[_myPicker selectRow:4 inComponent:1 animated:YES];
[self.view addSubview:_myPicker];
numberOfComponents:獲取指定列中的列表項的數量,只讀屬性
showsSelectionIndicato:是否顯示UIPickerView中的選中標記(以高亮背景作為選中標記)
-numberOfRowsInComponent: 獲取列的數量
-rowSizeForComponent: 獲取指定列中列表項的大小。返回CGSize對象
-selectRow:inComponent:animated:設置指定列的特定列表項。是否使用動畫
UIPickerViewDataSource :
控制包含多少列,每一列又包含多少列表項(也是是行)
//設置數據源方法,返回2表示有兩列
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 2;
}
//設置每一列,有多少行
// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
//先定義一個變量
NSInteger result;
//判斷
if (component == 0) {
//是第一列的時候,給5行
result = 5;
} else if (component == 1){
//第二列,給10行
result = 10;
}
//返回數值
return result;
}
//設置協議方法
//每一列寬度
// returns width of column and height of row for each component.
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
return 150;
}
//每一行顯示的數據
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
//返回的是NSString類型的數據
//返回每一行,因為索引是從0開始,+1
NSString *result = [NSString stringWithFormat:@"我是第%ld行",(long)row + 1];
return result;
}
UIpickerView.gif
PS:話說這個大概可以和日期相結合吧,回頭試一下