How do I change the color of the text in a UIPickerView under iOS 7?

Doug Smith picture Doug Smith · Oct 7, 2013 · Viewed 75.4k times · Source

I'm aware of the pickerView:viewForRow:forComponent:reusingView method, but when using the view it passes in reusingView: how do I change it to use a different text color? If I use view.backgroundColor = [UIColor whiteColor]; none of the views show up anymore.

Answer

Jon picture Jon · Nov 7, 2013

There is a function in the delegate method that is more elegant:

Objective-C:

- (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    NSString *title = @"sample title";
    NSAttributedString *attString = 
        [[NSAttributedString alloc] initWithString:title attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];

    return attString;
}

If you want to change the selection bar colors as well, I found that I had to add 2 separate UIViews to the view containing the UIPickerView, spaced 35 pts apart for a picker height of 180.

Swift 3:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {

    let string = "myString"
    return NSAttributedString(string: string, attributes: [NSForegroundColorAttributeName:UIColor.white])
}

Swift 4:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {

    let string = "myString"
    return NSAttributedString(string: string, attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])
}

Swift 4.2:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {

    let string = "myString"
    return NSAttributedString(string: string, attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
}

Remember when you use the method: You don't need to implement titleForRowInComponent() as it is never called when using attributedTitleForRow().