Change UIPicker color

13,756

Solution 1

Take a look at: http://makeapppie.com/tag/uipickerview-in-swift/

If you want to change your title color of each element you could implement:

func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let titleData = pickerData[row]
    var myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 15.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()])
    return myTitle
}

Swift 3:

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let titleData = pickerData[row]
    let myTitle = NSAttributedString(string: titleData!, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 15.0)!,NSForegroundColorAttributeName:UIColor.white])
    return myTitle
}

Solution 2

*For both Date picker and Normal Picker

   override func viewDidLoad() {
   super.viewDidLoad()
   pickerView.setValue(UIColor.blue, forKey: "textColor")
   pickerView.setValue(UIColor.black, forKey: "backgroundColor")
 }

Solution 3

Swift 4.0

func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
    let titleData = arrayOfPickerData[row]
    let myTitle = NSAttributedString(string: titleData, attributes: [.font:UIFont(name: "Georgia", size: 15.0)!, .foregroundColor:UIColor.white]))
    return myTitle
}

Solution 4

If you want more control customizing each element in the picker...

Use UIPickerViewDelegate's "viewForRow" method.

func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {

    var label: UILabel
    if let view = view as? UILabel { label = view }
    else { label = UILabel() }

    label.textColor = UIColor.blue
    label.textAlignment = .center
    label.font = UIFont(name: "My-Custom-Font", size: 20) // or UIFont.boldSystemFont(ofSize: 20)
    label.adjustsFontSizeToFitWidth = true
    label.minimumScaleFactor = 0.5
    label.text = getTextForPicker(atRow: row) // implemented elsewhere

    return label
}

Obviously the view you're returning could be more complex than just a UILabel.

Share:
13,756
user4671001
Author by

user4671001

Updated on August 03, 2022

Comments

  • user4671001
    user4671001 almost 2 years

    How can I change the color of my picker?

    I don't wish to change the font or the text. My picker is populate and works exactly how I want it, what I want to do is change the color from black to my custom white.

  • Karl Humphries
    Karl Humphries over 8 years
    This did exactly what I needed and enabled me to use white text in a picker view on a black background. Thank you
  • Raj Joshi
    Raj Joshi over 7 years
    @Youri Nooijen, great for me, Thanks.