在选择器视图中更改行颜色

时间:2012-08-23 20:50:03

标签: ios uipickerview

有没有办法在行中更改选择器视图对象颜色?

例如,您有addobject:@"black",但如何更改红色的字体颜色?

1 个答案:

答案 0 :(得分:1)

您可以使用UIView方法创建并填充自己的视图,而不是使用“title”委托方法。所以你创建了一个320宽的UIView,比如44高,在其中加上一个标签,设置标签文字和颜色,现在你有你想要的。

编辑:

#define PICKER_VIEW_SIZE CGSize(300, 40)

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return PICKER_VIEW_SIZE.height;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return PICKER_VIEW_SIZE.width;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    // assume one component, but this solutions works for multiple
    // lets do red, green, and blue alternating backgrounds with alternating black and white text

    UIColor *backgroundColor;
    switch(row % 3) {
    case 0:
    default:
        backgroundColor = [UICOlor redColor];
        break;
    case 1:
        backgroundColor = [UIColor blueColor];
        break;
    case 2:
        backgroundColor = [UIColor greenColor];
        break;
    }
    UIColor *textColor = (row % 2) ? [UIColor blackColor] : [UIColor whiteColor];

    UIView *view = [[UIView alloc] initWithFrame:(CGRect){ {0,0}, PICKER_VIEW_SIZE}];
    view.backgroundColor = backgroundColor;

    UILabel *label = [UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 20)];
    // configure the label
    label.text = text appropriate for this row;

    [view addSubview:label];

    return view;
}