Search code examples
iosswiftcolorsuipickerview

Strange Custom Background Color on UIPickerView Swift


I'm getting strange colors when assigning a custom UIColor to the background of UIPickerViews. I have created a color for textViews and pickerViews as follows:

let myTextViewBackgroundColor = UIColor(red: 192.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 0.35)

And I assign it as:

myTextView.backgroundColor = myTextViewBackgroundColor
keywordPicker.backgroundColor = myTextViewBackgroundColor

Here's what it looks like: enter image description here As you can see, the color of the textViews and the color of the picker are different. The difference seems more pronounced on a device than in this snapshot, but the custom color looks muddy, almost like it is mixed with a default gray background.

If I comment out the pickerView color item above, I get a gray color background: enter image description here If I choose a standard UIColor, it appears to work correctly. UIColor.yellowColor in this instance. If I choose white, that looks good, too. enter image description here I create the pickerView in code and assign it to a textField which has no background color assigned.

var keywordPicker : UIPickerView?

keywordPicker = UIPickerView()
keywordPicker?.delegate = self
keywordPicker?.dataSource = self

keywordsForItemTextField.inputView = keywordPicker
keywordPicker.backgroundColor = myTextViewBackgroundColor

And for what it's worth, I have a date picker that I created as a modal screen with it's own view controller. In that case, the picker is created on the storyboard. I still assign my background color with code and that picker shows the correct color.


Solution

  • tkanzakic's answer finally allowed me to change the background color of UIDatePicker.

    Here's the Swift 4 version:

    class CustomDatePicker: UIDatePicker {
    
        var customBackgroundColor = UIColor.black
    
        override func willMove(toWindow newWindow: UIWindow?) {
            super.willMove(toWindow: newWindow)
    
            if newWindow != nil {
                inputView?.backgroundColor = customBackgroundColor
            }
        }
    }
    

    Change the customBackgroundColor property to your liking.