iOS-选择器UIPickerView

前言:该选择器为iOS自带方法,可以用于任意需要选择的界面,如时间、地址等的选择,此处仅简略介绍其用法。使用UIPickerView必须声明协议,实现方法并设置代理。

UIPickerView的基本创建

1.UIPickerView的创建

    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.协议方法

#pragma mark-
//设定分区数,即该选择器有多少个列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return pickerArray.count;
}
//设定每个分区内的元素个数-(NSInteger)pickerView:(UIPickerView *)pickerViewnumberOfRowsInComponent:(NSInteger)component{   
NSArray * tmpArray = pickerArray[component];
    return tmpArray.count;
}
#pragma mark-
//设置选择器内元素显示的名字
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:
(NSInteger)row forComponent:(NSInteger)component{
NSArray * tmpArray = pickerArray[component];
return [tmpArray objectAtIndex:row];
}
//选中选择器元素(未拨动的部分为未选择状态)
-(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.附注(数据部分):

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];

附上相关资料,即UIPickerView常用的使用方法——与UITextField结合使用:选择器的使用


二、UIPickerView的常用方法

通过component确定其下的行数(从0开始)

theRow = [_pickerview selectedRowInComponent:theComponent];

备注

第一部分内容未使用markdown语法,代码结构比较混乱

你可能感兴趣的:(iOS-选择器UIPickerView)