前言:該選擇器為iOS自帶方法,可以用于任意需要選擇的界面,如時(shí)間、地址等的選擇,此處僅簡略介紹其用法。使用UIPickerView必須聲明協(xié)議,實(shí)現(xiàn)方法并設(shè)置代理。
UIPickerView的基本創(chuàng)建
1.UIPickerView的創(chuàng)建
UIPickerView * myPickerView = [[UIPickerView alloc]init];
myPickerView.frame = CGRectMake(0, HEIGHT_FOR_SCREEN - 150, WIDTH_FOR_SCREEN, 150);
myPickerView.dataSource = self;
myPickerView.delegate = self;
myPickerView.showsSelectionIndicator = YES;
myPickerView.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:myPickerView];
以上寫法僅為展示
2.協(xié)議方法
#pragma mark-<UIPickerViewDataSource>
//設(shè)定分區(qū)數(shù),即該選擇器有多少個(gè)列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return pickerArray.count;
}
//設(shè)定每個(gè)分區(qū)內(nèi)的元素個(gè)數(shù)-(NSInteger)pickerView:(UIPickerView *)pickerViewnumberOfRowsInComponent:(NSInteger)component{
NSArray * tmpArray = pickerArray[component];
return tmpArray.count;
}
#pragma mark-<UIPickerViewDelegate>
//設(shè)置選擇器內(nèi)元素顯示的名字
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:
(NSInteger)row forComponent:(NSInteger)component{
NSArray * tmpArray = pickerArray[component];
return [tmpArray objectAtIndex:row];
}
//選中選擇器元素(未撥動的部分為未選擇狀態(tài))
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:
(NSInteger)row inComponent:(NSInteger)component{
// [myTextField setText:[pickerArray objectAtIndex:row]];
NSArray * tmpArray = pickerArray[component];
switch (component) {
case 0:
yearStr = tmpArray[row];
break;
case 1:
monthStr = tmpArray[row];
break;
case 2:
dayStr = tmpArray[row];
break;
default:
break;
}
NSString * tmpTitleStr = [NSString stringWithFormat:@"%@ %@ %@",yearStr,monthStr,dayStr];
[myTimeButton setTitle:tmpTitleStr forState:(UIControlStateNormal)];
}
3.附注(數(shù)據(jù)部分):
yearArray = [[NSMutableArray alloc]initWithObjects:@"2015",@"2016",@"2017",@"2018",@"2019", nil];
monthArray = [[NSMutableArray alloc]initWithObjects:@"一月",@"二月",@"三月",@"四月", nil];
dayArray = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", nil];
pickerArray = [[NSMutableArray alloc]initWithObjects:yearArray,monthArray,dayArray, nil];
yearStr = [[NSString alloc]init];
monthStr = [[NSString alloc]init];
dayStr = [[NSString alloc]init];
附上相關(guān)資料,即UIPickerView常用的使用方法——與UITextField結(jié)合使用:選擇器的使用
二、UIPickerView的常用方法
通過component確定其下的行數(shù)(從0開始)
theRow = [_pickerview selectedRowInComponent:theComponent];
備注
第一部分內(nèi)容未使用markdown語法,代碼結(jié)構(gòu)比較混亂