繁体   English   中英

iOS14 - 如何更改UIKit中UIDatePicker的textColor?

[英]iOS14 - How to change textColor of UIDatePicker in UIKit?

使用 iOS14.0.1, Swift5.3, Xcode12.0.1,

我尝试在 iOS14 中更改UIDatePickertextColor并使用 UIKit。

在这里读到你需要以下方法来做到这一点:

let myDatePicker = UIDatePicker()
myDatePicker.tintColor = .white

我还尝试了以下方法(但这会使我的应用程序在 iOS14 下崩溃):

myDatePicker.setValue(UIColor.white, forKeyPath: "textColor")

我也尝试过(但也没有成功):

UILabel.appearance(whenContainedInInstancesOf: [UIDatePicker.self]).textColor = UIColor.white

在 light 模式下,我的所有试验都不起作用(从截图摘录中可以看出):

在此处输入图像描述

我需要做什么才能在我的UIDatePicker中获取白色文本?

试试这个,在下面添加扩展名:

extension UIDatePicker {

var textColor: UIColor? {
    set {
        setValue(newValue, forKeyPath: "textColor")
    }
    get {
        return value(forKeyPath: "textColor") as? UIColor
    }
  }
}

现在在 viewDidLoad 调用中:

myDatePicker.textColor = .yourColor

在其他选择器属性之后调用它,es.:

myDatePicker.preferredDatePickerStyle = .wheels
myDatePicker.addTarget(self, action: #selector(handleDatePicker), for: .valueChanged)
myDatePicker.datePickerMode = .dateAndTime
myDatePicker.timeZone = NSTimeZone.local
myDatePicker.backgroundColor = .black
myDatePicker.setValue(false, forKey: "highlightsToday")
myDatePicker.textColor = .yourColor // here

在此处输入图像描述

如果你想要 highlightsToday 将相对选择器值设置为 true:

myDatePicker.setValue(true, forKey: "highlightsToday")

这是结果:

在此处输入图像描述

是的,它有效,但是,属性preferredDatePickerStyle =.wheels必须在textColor =.yourColor之前设置,否则属性textColor可能永远不会受到影响。

我使用pickerView delegate方法更改选择器视图颜色。 您可以添加此 function 添加这些委托方法: UIPickerViewDelegate, UIPickerViewDataSource

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

      // change your picker view textColor etc. in here..
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM