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.
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.
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.
This code is working for me
func textFieldDidBeginEditing(_ textField: UITextField) {
let picker = UIDatePicker()
picker.datePickerMode = .date
textField.inputView = picker
textField.inputView?.backgroundColor = UIColor.blue
}
Even on the first edit it shows up blue.
Also:
Instead of creating a picker instance inside textField delegate method, you could create the picker in viewDidLoad method, set its background color, give it a tag and then access this picker using the tag in the delegate method instead of creating the variable there.
You could use the following library for custom colours https://github.com/prolificinteractive/PIDatePicker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With