iOS开发 - 改变picker选中行字体颜色

1,197 阅读1分钟

平日里的picker都适用默认的,也没有刻意去自定义什么,原生的控件比如picker,还是很美观的,真要自己去改变点什么就是给自己找不自在了,简单的自定义如颜色,字体,分割线颜色还可以调,如果涉及到更多更大的变化就只能自己写了,下面就来说说如何自定义颜色,字体,分割线颜色,以及选中时picker的颜色怎么来设置(默认你已经会使用picker的基本功能,网上有很多,这里不再说明):

//关键操作在下面的两个代理方法中,请看
#pragma mark UIPickerViewDelegate 代理方法
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    //设置分割线的颜色
    for(UIView *singleLine in pickerView.subviews)
    {
        if (singleLine.frame.size.height < 2)
        {
            singleLine.backgroundColor = [UIColor colorWithRed:0.75f green:0.75f blue:0.75f alpha:1.00f];
        }
    }
    //设置文字的属性(改变picker中字体的颜色大小)
    UILabel *reasonLabel = [UILabel new];
    reasonLabel.textAlignment = NSTextAlignmentCenter;
    reasonLabel *reasonModel = _reasonArray[row];
    reasonLabel.text = reasonModel.sh_reason_text;
    reasonLabel.font = [UIFont systemFontOfSize:14];
    reasonLabel.textColor = RGBCOLOR(102, 102, 102);
    //改变选中行颜色(设置一个全局变量,在选择结束后获取到当前显示行,记录下来,刷新picker)
    if (row == selectRow) {
    //改变当前显示行的字体颜色,如果你愿意,也可以改变字体大小,状态
        reasonLabel.textColor = RGBCOLOR(34, 34, 34);
    }

    return reasonLabel;
}

// 选中行显示在label上
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    ReasonModel *reasonModel = _reasonArray[row];
    resaonType = [NSString stringWithFormat:@"%@-%@",reasonModel.sh_reason_id,reasonModel.sh_reason_text];
    //记录下滚动结束时的行数
    selectRow = row;
    //刷新picker,看上面的代理
    [pickerView reloadComponent:component];
}

总结:美中不足的是,只能在picker滚动结束后才能改变当前行颜色,在滚动中路过的那些行,字体颜色不能改变,可以考虑自定义控件,可能会比较复杂,看需求,斟酌使用。