How to change background color of UIDatePicker set as UITextField inputView?

Viewed 5356

Please do not mark as duplicate. The available answers haven't answered my issue.

I am using a UIDatePicker as UITextField's inputView (inside a UITableViewCell):

@IBOutlet weak var theTextField: UITextField!

func textFieldDidBeginEditing(_ textField: UITextField) {

        let picker = UIDatePicker()
        picker.setValue(Colors.CI2, forKeyPath: "textColor")

        picker.datePickerMode = .date

        textField.inputView = picker
        textField.inputView?.backgroundColor = Colors.CI1 // my desired color

        picker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)

}

The problem: The color does only change, once the picker is called a second time.

enter image description here enter image description here

I guess, that this issue occurs because the inputView is optional and only once the picker is called a second time, the inputView is instantiated at the moment where I want to change the color.

I have tried to subclass UITextField and observe inputView.

class DateTextField: UITextField {

    override var inputView: UIView? {

        didSet {

            self.inputView?.backgroundColor = Colors.CI1
            self.reloadInputViews()

        }

    }

}

Unfortunately without success. Same behavior. What am I missing? Help is very appreciated.

6 Answers
Related