change global textcolor of UIPickerView possible?

Viewed 451

I am having trouble with two of my pickerViews. I am wondering if it is possible to change the global text color of my pickerViews in the AppDelegate file?

I know some stuff can be done like:

UIPickerView.appearance().backgroundColor = color6
UIPickerView.appearance().tintColor = color4

If I need to write it in my code manually in each pickerView. What sort of pickerView should it be coded into, titleForRow?

1 Answers

Try to use the following class. I have subclassed the UIPickerView and specified colours inside. This is working fine. when you set the items. it will set delegate and datasource to self and will do the job for you.

   import UIKit
    class CustomUIPickerView: UIPickerView{
        let textColor: UIColor = .white
        let backGroundColor: UIColor = .blue
        let _tintColor: UIColor = .white
        var items: [String]?{
            didSet{
                self.delegate = self
                self.dataSource = self
                self.reloadAllComponents()
            }
        }
        override init(frame: CGRect) {
            super.init(frame: frame)
           commonInit()
        }

        func commonInit(){
            self.backgroundColor = backGroundColor
            self.tintColor = _tintColor
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            commonInit()
        }
    }
    extension CustomUIPickerView: UIPickerViewDataSource{
        func numberOfComponents(in pickerView: UIPickerView) -> Int {
            return 1
        }

        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
            return self.items?.count ?? 0
        }

    }
    extension CustomUIPickerView: UIPickerViewDelegate{
        func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
            let string = self.items?[row] ?? ""
            return NSAttributedString(string: string, attributes: [NSAttributedStringKey.foregroundColor: textColor])
        }
    }

However if you want to handle the delegate and datasource in your view controller then you can take the advantage of using Extensions here is how:

extension String{
    func stringForPickerView() -> NSAttributedString{
        let color: UIColor = .white
        return NSAttributedString(string: self, attributes: [NSAttributedStringKey.foregroundColor: color])
    }
}

then in your ViewController:

extension ViewController: UIPickerViewDelegate{
    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        return self.items[row].stringForPickerView() // from Extension
    }
}
Related