Steve B
Steve B

Reputation: 911

How to change the UIPickerView text color?

The default UIPickerView color for text is black. There has been some updates to the language in Swift4. I have found my own solution and answered below.

Upvotes: 27

Views: 18932

Answers (5)

zouritre
zouritre

Reputation: 655

In storyboard you can add textColor to Key Path:

Upvotes: 8

Colby Hill
Colby Hill

Reputation: 1110

Updated for Swift 5:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    return NSAttributedString(string: parksPickerData[row], attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])
}

Upvotes: 12

ainareta685
ainareta685

Reputation: 149

I have a project with PickerViews and DatePickers (inside a TableViewCell), and I had to use a different sentence for each case.

For PickerViews:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        let titleData = "data"
        let myTitle = NSAttributedString(string: titleData, attributes: [NSAttributedString.Key.foregroundColor: UIColor.lightGray])

        return myTitle
    }

For DatePicker:

datePicker.setValue(UIColor.lightGray, forKey: "textColor")

Upvotes: 4

Steve B
Steve B

Reputation: 911

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    return NSAttributedString(string: data[row], attributes: [NSAttributedStringKey.foregroundColor: UIColor.yellow])        
}

Upvotes: 39

Matthew Bradshaw
Matthew Bradshaw

Reputation: 1863

You could use:

pickerView.setValue(UIColor.yellow, forKeyPath: "textColor")

This will only change the color for the currently selected row.

See also: https://stackoverflow.com/a/9866686/5306470

Upvotes: 14

Related Questions