UIPickerView
UIPickerView
主要使用场景:日期栏,地址栏
与tableview类似都有delegate和DataSource。
UIPickerViewDelegate,UIPickerViewDataSource
基本使用方法
日历的模板为例子,在新建的.m文件里面
UIPickerView *yearPicker = [[UIPickerView alloc]init]; // yearPicker 用的当前页面的全局变量
yearPicker.delegate = self;
yearPicker.dataSource = self;
[viewDateBg addSubview:yearPicker]; // viewDateBg是我自己新建的背景视图
[yearPicker mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(labDataTitle.mas_bottom);
make.left.offset(20.5);
make.width.offset(63);
make.height.offset(140);
}];
需要实现的代理方法
// 选择的每一个row需要展示的数据
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
// 显示多少个组件 类似于tableview的section
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
// 每个组件显示多少行 类似于tableview的row
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return self.yearArray.count;
}
// 每行的高度
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
return 48;
}
// 每个组件的宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{
return 64 ;
}
每一行需要显示的数据
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
UILabel *rowLabel = [[UILabel alloc]init];
rowLabel.textAlignment = NSTextAlignmentCenter;
rowLabel.backgroundColor = [UIColor clearColor];
rowLabel.frame = CGRectMake(0, 0, 39,300);
rowLabel.textAlignment = NSTextAlignmentCenter;
rowLabel.font = [UIFont systemFontOfSize:17];
rowLabel.textColor = [UIColor grayColor];
[rowLabel sizeToFit];
rowLabel.text = [NSString stringWithFormat:@"%ld",(long)row];
return rowLabel;
}
最后运行出来的效果
标题上面的是简单的使用该控件,在日常生活中我们可能会使用的更复杂一些。类似于下图的功能。
需要查看以上效果的完整代码,请访问。
https://github.com/cymInSHRelese/DateUIPickerView.git
使用中遇到的问题,如何问题定位,问题解决
iOS14.1之前,在使用这个自定义控件的时候,为了去除选中row的上下两个黑色的横线,做了一个设置,如下。
这段代码是我在网上搜的内容,当时确实有效果,就一直在使用。 但是在iOS14.1系统上这个方法就不能使用了,会闪退。
原因就是pickerview只有两层视图,没有第三层,强制访问会造成数组越界。
// [pickerView.subviews[1] setBackgroundColor:[UIColor clearColor]];
// [pickerView.subviews[2] setBackgroundColor:[UIColor clearColor]];
这次的问题出现让我有了新的感悟。
项目运行出现问题的时候,先不要慌张。查看一下日志,看是什么 原因造成的,然后看是在哪一个类里面出现的问题,定位到类之后,一般日志里面还会打印出来是哪一个方法或者函数造成的程序运行失败。这对于定位问题有很大的帮助。之后就是针对问题查找解决方法了。有时候,我们自己可以解决,有时候就需要借助网络来查询。
解决之后,对于该问题就要做记录了。记录问题出现的原因及解决方案。