更改UIPickerView pickerView:viewForRow:基于特定条件的属性

时间:2014-04-25 09:58:21

标签: ios uipickerview

我正在尝试根据特定条件更改viewForRow中的文字颜色。当我按下按钮时,视图会变为不同的颜色,但我还想更改选择器中文本的颜色。我使用' viewForRow'因为我有自定义视图。

//adds subcategories to the wheel
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, pickerView.frame.size.width, 44)];
    label.backgroundColor = [UIColor clearColor];


    if (!self.isBackgroundWhite)//Boolean that changes when the background changes
    {
        NSLog(@"Set white text");
        label.textColor = [UIColor whiteColor];

    }else{

        label.textColor = [UIColor blackColor];
    }



    if (row == 1) {
        label.text = [NSString stringWithFormat:@"  %@",[self.servicesArray objectAtIndex:row]];
        label.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
    }else{
        label.text = [NSString stringWithFormat:@"     -%@",[self.servicesArray objectAtIndex:row] ];
        label.font = [UIFont fontWithName:kAppFont size:16];
    }
        return label;
}

编辑:感谢@Rich我能够发现我的问题,我只需要致电[self.pickerView reloadAllComponents];

1 个答案:

答案 0 :(得分:2)

如果您只想更改文字颜色,请使用其他委托方法pickerView:attributedTitleForRow:forComponent:

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{

    NSString *title;
    UIFont *font;
    if (row == 1) {
        title = [NSString stringWithFormat:@"  %@",[self.servicesArray objectAtIndex:row]];
        font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:18];
    } else{
        title = [NSString stringWithFormat:@"     -%@",[self.servicesArray objectAtIndex:row] ];
        font = [UIFont fontWithName:kAppFont size:16];
    }

    UIColor *textColor;
    if (self.isBackgroundWhite) {
        textColor = [UIColor blackColor];
    } else {
        NSLog(@"Set white text");
        textColor = [UIColor whiteColor];
    }

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paragraphStyle.alignment = NSTextAlignmentLeft;

    NSDictionary *attributes = @{NSForegroundColorAttributeName : textColor, 
                                            NSFontAttributeName : font,
                                  NSParagraphStyleAttributeName : paragraphStyle};

    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

另请注意,更改[self.pickerView reloadAllComponents];时应致电isBackgroundWhite。我会通过覆盖backgroundWhite的setter并在布尔值更改时重新加载选择器视图来完成此操作。

编辑:
似乎有一个' bug' (有意或无意)在iOS 7中(在iOS 6上正常工作),在UIFont方法返回的NSAttributedString上设置pickerView:attributedTitleForRow:forComponent:。因此,虽然上述适用于文本颜色,但字体不会改变。幸运的是,您可以使用问题中的代码来解决这个问题。有关详细信息,请参阅this answer