iOS UIPickerView 改变字体颜色,分割线颜色和尺寸和添加图片

苹果选择器,还是比较方便使用的,但是每次,UI设计师都会有自己的独特见解,哈哈,有点意思。有一个开源的框架自定义程度还挺高的,好像是通过UITableView 来做的。还挺有意思的,大家可以去看看。传送门 -- PGDatePicker

下面针对UIPickerView 做一些调整,先看效果图。


效果图

下面是实现代码:Demo

原理:就是在复用的时候,进行修改。和 UITableView 自定义Cell 等类似。

- (UIView *)pickerView:(UIPickerView *)pickerView
            viewForRow:(NSInteger)row forComponent:(NSInteger)component
           reusingView:(UIView *)view{
    
    //普通状态的颜色
    UILabel* norLabel = (UILabel*)view;
    if (!norLabel){
        norLabel = [[UILabel alloc] init];
        norLabel.textColor = [UIColor grayColor];
        norLabel.adjustsFontSizeToFitWidth = YES;
        [norLabel setTextAlignment:NSTextAlignmentCenter];
        [norLabel setBackgroundColor:[UIColor blueColor]];
        [norLabel setFont:[UIFont systemFontOfSize:13]];
        
        //icon
        UIImageView *av = [[UIImageView alloc] initWithFrame:CGRectMake(30, 3, 20, 20)];
        av.image = [UIImage imageNamed:[NSString stringWithFormat:@"img_%d", (int)row%2]];
        [norLabel addSubview:av];
    }
    norLabel.text = [self pickerView:pickerView
                            titleForRow:row
                           forComponent:component];
    
    //当前选中的颜色
    UILabel *selLb = (UILabel*)[pickerView viewForRow:row forComponent:0];
    if (selLb) {
        selLb.textColor = [UIColor brownColor];
        selLb.adjustsFontSizeToFitWidth = YES;
        [selLb setTextAlignment:NSTextAlignmentCenter];
        [selLb setBackgroundColor:[UIColor purpleColor]];
        [selLb setFont:[UIFont systemFontOfSize:16]];
    }
    
    //下一个选中的颜色(为了选中状态不突兀,自己注释看看效果)
    UILabel *selLb1 = (UILabel*)[pickerView viewForRow:row + 1 forComponent:0];
    if (selLb1) {
        selLb1.textColor = [UIColor redColor];
        selLb1.adjustsFontSizeToFitWidth = YES;
        [selLb1 setTextAlignment:NSTextAlignmentCenter];
        [selLb1 setBackgroundColor:[UIColor greenColor]];
        [selLb1 setFont:[UIFont systemFontOfSize:16]];
    }
    
    //设置分割线
    for (UIView *line in pickerView.subviews) {
        if (line.frame.size.height < 1) {//0.6667
            line.backgroundColor = [UIColor blackColor];
            CGRect tempRect = line.frame;
            CGFloat lineW = 120;
            line.frame = CGRectMake((pickerView.frame.size.width - lineW) * 0.5, tempRect.origin.y, lineW, 2);
        }
    }
    
    return norLabel;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,142评论 1 32
  • 记录一次比较诡异的mysql死锁日志。系统运行几个月来,就在前几天发生了一次死锁,而且就只发生了一次死锁,整个排查...
    枫叶_huazhe阅读 2,050评论 0 5
  • 感谢亲爱的自己 1.过得充实又有质量,平静轻安的刻度稳稳的。为自由喜悦打扎实基础 2.学费交了,进度很可控。关键时...
    Only唯阅读 406评论 0 2
  • 很久没有提起笔写过什么了,久的似乎都已忘记了自己还会写字,忘记了从前的自己。从前的自己什么样呢,真的不记得...
    陌上木木阅读 450评论 1 2
  • 你是天域里的雪花, 透着清澈,晶莹的光芒 你是世间美丽的尤物, 我的黝黑眼眸里, 也微泛起白光点滴 似你,是你, ...
    深自缄默阅读 227评论 0 0