更改UIPickerView的全局文本颜色可能吗?

时间:2017-06-04 20:45:49

标签: swift3 uipickerview

我的两个pickerView遇到了问题。我想知道是否可以在AppDelegate文件中更改pickerViews的全局文本颜色?

我知道有些东西可以像:

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

如果我需要在每个pickerView中手动编写代码。应该将哪种pickerView编码为titleForRow?

1 个答案:

答案 0 :(得分:3)

尝试使用以下类。我已经将UIPickerView和指定的颜色子类化了。这工作正常。设置项目时。它会将委托和数据源设置为自己,并为您完成工作。

   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])
        }
    }

但是,如果您想在视图控制器中处理委托和数据源,那么您可以利用扩展来实现以下优势:

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

然后在你的ViewController中:

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