Change UIDatePicker font color?

后端 未结 15 1732
南方客
南方客 2020-12-04 19:12

All I want to do is change the font color of the UIDatePicker. I\'ve researched other questions but they\'re all involving changing other properties and customizing the enti

相关标签:
15条回答
  • 2020-12-04 20:03

    If anyone wants the swift solution, I placed the following in viewDidLoad:

        birthdayDatePicker.setValue(DesignHelper.getOffWhiteColor(), forKey: "textColor")
        birthdayDatePicker.performSelector("setHighlightsToday:", withObject:DesignHelper.getOffWhiteColor())
    
    0 讨论(0)
  • 2020-12-04 20:03

    Add Runtime Attribute named "textColor" from Storyboard as shown in following image.

    0 讨论(0)
  • 2020-12-04 20:04

    To change UIDatePicker text color use:

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

    It works like a charm with xCode 7.3 and Swift 2.3.

    0 讨论(0)
  • 2020-12-04 20:07

    It didn't work until textColor was set inside layoutSubviews()

    override func layoutSubviews() {
        super.layoutSubviews()
        datePicker.backgroundColor = .black
        datePicker.setValue(.white, forKeyPath: "textColor")
    }
    
    0 讨论(0)
  • 2020-12-04 20:09

    One other alternative to @Jeremiah answer is to define those values in Interface Builder. I prefer this one because there is no code to add in your ViewController.

    Click into your DatePicker view and customise it from the Attribute inspector as in the screenshot. screenshot

    Works for Swift 2, 3, 4 and probably for Swift < 2. (not tested)

    0 讨论(0)
  • 2020-12-04 20:09

    As alternative to @Jeremiah answer, you can use this:

    datePicker.setValue(UIColor.redColor(), forKey: "textColor")
    datePicker.sendAction("setHighlightsToday:", to: nil, forEvent: nil)
    datePicker.setDate(NSDate(timeIntervalSinceReferenceDate: 0), animated: false)
    

    it will remove Today (you will see current date), but it will be with right color.

    Possible troubles: if you change color dynamically, I didn't find a way to reload date picker. So, the user will see previous color and only after scroll, color will changed to a new one. -> Solved, by last string. Looks like Voodoo, but it works...

    This answer suitable for Swift 2.1

    0 讨论(0)
提交回复
热议问题