Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 705
David Seek Avatar asked Jul 05 '17 18:07

David Seek


3 Answers

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

like image 163
David Seek Avatar answered Oct 18 '22 00:10

David Seek


This code is working for me

func textFieldDidBeginEditing(_ textField: UITextField) {   
        let picker = UIDatePicker()
        picker.datePickerMode = .date

        textField.inputView = picker
        textField.inputView?.backgroundColor = UIColor.blue

}

Screenshot

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.

like image 3
Rishabh Avatar answered Oct 18 '22 00:10

Rishabh


You could use the following library for custom colours https://github.com/prolificinteractive/PIDatePicker

like image 2
A.S Avatar answered Oct 18 '22 00:10

A.S