iOS14 - 如何在UIKit中更改UIDatePicker的文本颜色?

4

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

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

我在这里阅读到需要使用以下方法:

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

我还尝试了以下方法(但这会导致我的应用在iOS14下崩溃):
myDatePicker.setValue(UIColor.white, forKeyPath: "textColor")

我也尝试过(但也没有成功):
UILabel.appearance(whenContainedInInstancesOf: [UIDatePicker.self]).textColor = UIColor.white

在浅色模式下,我的尝试都无法正常工作(可以在屏幕截图中看到):

enter image description here

我需要做些什么才能让我的 UIDatePicker 文本是白色的?


如果您有使用此功能的用例,请向苹果提交增强请求。 - matt
3个回答

4

尝试这个,添加下面的扩展:

extension UIDatePicker {

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

现在在viewDidLoad中调用:
myDatePicker.textColor = .yourColor

在其他选择器属性之后调用它,例如:

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

enter image description here

如果您想要高亮显示今天,请将相对选择器的值设置为 true:

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

这是结果:

enter image description here


2
谢谢Fabio - 我还没有时间测试你的解决方案。你确定它能在iOS14中工作吗?因为forKeyPath: "textColor"在iOS14中似乎不再起作用了。或者你自己的扩展实现仍然可行吗? - iKK
1
@iKK 你好,我在 Xcode 12 - iOS 14 上运行它... 它像魔法一样工作。 - Fabio
在我的情况下,在iOS 14中它不起作用。有人找到解决方案了吗?myDatePicker.setValue(true, forKey: "highlightsToday") 在iOS 14中崩溃。 - Raspberry
@AiyubMunshi 在声明 myDatePicker 背景颜色后,只需调用值键即可...现在不会崩溃了,我已更新我的答案,感谢您的提醒!!! - Fabio
无法在 iOS 16 beta 上工作。 - Rajasekhar Pasupuleti
显示剩余2条评论

3

没问题!但是,必须在设置 textColor = .yourColor 之前先设置属性 preferredDatePickerStyle = .wheels,否则可能永远不会影响属性 textColor


0

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

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

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

谢谢Mehmett - 我也会尝试这个解决方案... - iKK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接