Search code examples
iosswiftuipickerview

Extend UIPickerView to change title color


I would like all UIPickerViews in an app to have white text. I can make it work fine for an individual pickerview, but I would like to have it apply to all occurrences.

I got this far...

extension UIPickerView {
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let titleData = ?????
    let colorTitle = NSAttributedString(string: titleData, attributes: [NSForegroundColorAttributeName:UIColor.whiteColor()])
}

However, I don't want to actually change the text... just the color. How can I grab the title (text) for the specified row so that I can returned it as an NSAttributedString?

Thanks.


Solution

  • I ended up creating a subclass of UIDatePicker and overriding the addSubView method. The code below is working well for me.

    class ColoredDatePicker: UIDatePicker {
        var changed = false
        override func addSubview(view: UIView) {
            if !changed {
                changed = true
                self.setValue(UIColor.whiteColor(), forKey: "textColor")
            }
            super.addSubview(view)
        }
    }