在 Swift 中为 UIDatePicker 设置文本颜色

4

我一直在尝试设置UIDatePicker的字体和颜色,但是今天datePickerlabel的颜色没有改变。我的应用程序中其他部分都相对容易调整,只有这个有些麻烦。有人知道如何做吗?

func updatedatePicker(){                
    DatePicker.setValue(UIColor.whiteColor(), forKeyPath: "textColor")
    DatePicker.setValue(1, forKeyPath: "alpha")    
}

viewDidLoad()中:-
DatePicker.addTarget(self, action: #selector(ViewController.updatedatePicker), forControlEvents: UIControlEvents.ValueChanged)

可能是Change UIDatePicker font color?的重复问题。 - Daniel Sumara
这里有一种优雅的方法可以使用扩展来实现。 - Omar Albeik
3个回答

7
我曾经遇到过同样的问题,所以我尝试了一些方法,将 datePickerMode 更改为其他模式,它会重新绘制并使用新设置的 textColor,而且不要在 updatedatePicker 函数中设置 textColor,也要像这样在 viewDidLoad 中设置。

答案已更新至最新的 Swift 4 版本。

override func viewDidLoad() {
    super.viewDidLoad()
    datePicker.setValue(UIColor.white, forKeyPath: "textColor")
    datePicker.datePickerMode = .date
    datePicker.datePickerMode = .dateAndTime //Set here that mode you want.
    datePicker.addTarget(self, action: #selector(selectedDate), for: .valueChanged)
}

在iOS 14-16版本中,这个功能无法正常工作。请参考:https://developer.apple.com/forums/thread/711760 - undefined

1
如果您的解决方案无法生效,您可以尝试通过检查器添加外部颜色,就像这样:

enter image description here


1
要更改UIDatePicker文本颜色,请使用:

    // MARK: - Helping content 

    private enum DatePickerProperties: String {
        case TextColor = "textColor"
        case HighlightsToday = "highlightsToday"
    }

    // MARK: - Outlets

    @IBOutlet private weak var datePicker: UIDatePicker!

    // MARK: - Lifecicle

    public override func awakeFromNib() {
        super.awakeFromNib()

        self.datePicker.setValue(UIColor.whiteColor(), forKey: DatePickerProperties.TextColor.rawValue)
        self.datePicker.setValue(false, forKey: DatePickerProperties.HighlightsToday.rawValue)
    }

它与xCode 7.3和Swift 2.3完美配合。

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