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-<UIPickerViewDataSource>
//设定分区数,即该选择器有多少个列
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return pickerArray.count;
}
//设定每个分区内的元素个数-(NSInteger)pickerView:(UIPickerView *)pickerViewnumberOfRowsInComponent:(NSInteger)component{   
NSArray * tmpArray = pickerArray[component];
    return tmpArray.count;
}
#pragma mark-<UIPickerViewDelegate>
//设置选择器内元素显示的名字
- (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语法,代码结构比较混乱

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • UIPickerView也是一个选择器控件,它比UIDatePicker更加通用,它可以生成单列的选择器,也可生成...
    小蘑菇2阅读 8,967评论 3 5
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一种新的协议。它实...
    香橙柚子阅读 24,347评论 8 183
  • 回到学校后生活又归于宁静,日子像是小溪水一样缓缓地流淌,看起来悠闲但似乎又没有一刻能停下来,偶尔也会想起表哥,跟他...
    但山远阅读 7,782评论 9 10
  • 人生什么最重要?选择! 什么决定选择?价值观。 价值观是由多种原则概念组成的,要不断打磨增加原则,形成系统的原则概...
    游博铭阅读 1,684评论 0 0
  • Array中的方法 四个方面去学习数组的方法 方法的作用 是否传递参数 有没有返回值 原数组是否发生改变 注意: ...
    不是王小贱阅读 3,085评论 0 3

友情链接更多精彩内容