Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the line color of a UIDatePicker

I have got a UIDatePicker in one of my ViewControllers. As you can see, the background is dark.

Image of my UIDatePicker

What i already managed to change is the text color to white. What i just can't change is the color of the two lines above and below the selected date. It always remains default dark grey. Does anyone have a code snipped to achieve coloring these lines?

like image 701
LeMark88 Avatar asked Nov 18 '15 19:11

LeMark88


2 Answers

huniser_suraj answer is correct, just use additional check for future changes, this is how I use it, for UIPickerView & UIDatePicker, respectively:

    for subview in self.picker.subviews {

        if subview.frame.height == 1 {

            subview.backgroundColor = UIColor.whiteColor()
        }
    }

    if let pickerView = self.datePicker.subviews.first {

        for subview in pickerView.subviews {

            if subview.frame.height == 1 {

                subview.backgroundColor = UIColor.whiteColor()
            }
        }
    }

iOS 10 UPDATE

From iOS 10 on, this doesn't work anymore, as mentioned in some of the comments, i.e. finding the subviews & getting to them works, but setting the background color doesn't work anymore. I did another dirty solution for this, I'm setting a border with a border color which works.

    for subview in self.picker.subviews {

        if subview.frame.height <= 5 {

            subview.backgroundColor = UIColor.white
            subview.tintColor = UIColor.white
            subview.layer.borderColor = UIColor.white.cgColor
            subview.layer.borderWidth = 0.5            }
    }

    if let pickerView = self.datePicker.subviews.first {

        for subview in pickerView.subviews {

            if subview.frame.height <= 5 {

                subview.backgroundColor = UIColor.white
                subview.tintColor = UIColor.white
                subview.layer.borderColor = UIColor.white.cgColor
                subview.layer.borderWidth = 0.5
            }
        }
        self.datePicker.setValue(UIColor.white, forKey: "textColor")
    }
like image 125
Kex Avatar answered Sep 21 '22 08:09

Kex


To start with, Apple docs says, about Date Pickers, "You cannot customize the appearance of date pickers."

That being said, the following code does exactly what you need. I understand it's not the most elegant piece of code, but here it is

datePicker.subviews[0].subviews[1].backgroundColor = UIColor.redColor()
datePicker.subviews[0].subviews[2].backgroundColor = UIColor.redColor()

UIDatePicker has a subview, UIDatePickerView, which has 3 subviews, 2 of the latter of which are the two lines that indicate the selection row.

like image 31
SrB Avatar answered Sep 21 '22 08:09

SrB