David Seek David Seek - 6 months ago 43
Swift Question

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

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.

Answer Source

The mistake was that I had set the keyboard appearance in the Interface Builder. Once set back to default it worked like it was supposed to.

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download