gpt4 book ai didi

swift3 - 可以更改 UIPickerView 的全局文本颜色吗?

转载 作者:行者123 更新时间:2023-12-02 01:05:35 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

尝试使用以下类。我已经对 UIPickerView 进行了子类化并在其中指定了颜色。这工作正常。当您设置项目时。它将把委托(delegate)和数据源设置为 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])
}
}

但是,如果您想在 View Controller 中处理委托(delegate)和数据源,那么您可以利用扩展,具体方法如下:

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

关于swift3 - 可以更改 UIPickerView 的全局文本颜色吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44358615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com