Swift3 是否可能更改UIPickerView的全局文本颜色?

Swift3 是否可能更改UIPickerView的全局文本颜色?,swift3,uipickerview,Swift3,Uipickerview,我的两个pickerViews有问题。我想知道是否可以在AppDelegate文件中更改pickerViews的全局文本颜色 我知道可以做一些事情,比如: UIPickerView.appearance().backgroundColor = color6 UIPickerView.appearance().tintColor = color4 如果我需要在每个pickerView中手动在代码中编写它。它应该编码成什么样的pickerView,titleForRow?尝试使用以下类。我对UIP

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

我知道可以做一些事情,比如:

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

如果我需要在每个pickerView中手动在代码中编写它。它应该编码成什么样的pickerView,titleForRow?

尝试使用以下类。我对UIPickerView进行了子分类,并在其中指定了颜色。这很好用。当您设置项目时。它将委托和数据源设置为self,并将为您完成这项工作

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

例如,您可以为
UIPickerView
编写扩展或子类,并在
init
函数中设置色调颜色。这将阻止您编写重复的代码。嗨,Linus,谢谢您的评论!好的,这是否意味着我应该为颜色创建一个类并像这样添加uipickerView?类颜色:UIPickerView{}否。创建选择器视图的子类:
类MyPickerView:UIPickerView{…}
。然后,编写一个自定义初始化函数并在其中设置默认的着色颜色。@Adrian请检查我的更新answer@SahilManchanda我刚看到这个。我明天要看一眼。非常感谢,太棒了!它工作得很好。我创建的自定义类做得不够。非常感谢你!它还不让我接受,但我会在赏金到期时接受。