sam k
sam k

Reputation: 1107

How to change the UIDatePicker backgroundColor? in Swift 3.0

I am adding a datePicker for my keyboard on a textfield. I am able to change the datePicker text color or even its alpha but Im not able to change its backgroundColor even though the option is given to me.

I know the UIDatePicker is not very customizable but since there is a backgroundColor option is being given to me i'm surprised why it doesnt change.

Any thoughts?

Here is my code:

    datePickerView.backgroundColor = .clear
    datePickerView.setValue(backgroundTint, forKeyPath: "textColor")
    datePickerView.datePickerMode = UIDatePickerMode.date
    inputView.addSubview(datePickerView)

EDIT

Im writing my code in a subclass of UITableViewCell --->

import UIKit

class AgeTableViewCell: UITableViewCell, UITextFieldDelegate {

let maxLength: Int = 10
let ageTextField = ProfileNameUITextField()

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    
    self.contentView.addSubview(ageTextField)
    
    self.contentView.backgroundColor = .clear

    if self.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
        self.separatorInset = UIEdgeInsets.zero
    }
    if self.responds(to:#selector(setter: UIView.layoutMargins)) {
        self.layoutMargins = UIEdgeInsets.zero
    }
    if self.responds(to: #selector(setter: UIView.preservesSuperviewLayoutMargins)) {
        self.preservesSuperviewLayoutMargins = false
    }
}

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
}

override func layoutSubviews() {
    super.layoutSubviews()
    
    let width = self.bounds.width
    let height = self.bounds.height
    let borderWidth: CGFloat = 1.0
    let color = UIColor.white.withAlphaComponent(0.1)
    ageTextField.frame = CGRect(x: 0.0, y: borderWidth, width: width - borderWidth, height: height - 2 * borderWidth)
    ageTextField.borderStyle = .none
    ageTextField.backgroundColor = color
    ageTextField.textColor = .white
    ageTextField.tintColor = .white
    ageTextField.delegate = self
    ageTextField.attributedPlaceholder = NSAttributedString(string:"Birth Date",
                                                            attributes:[NSForegroundColorAttributeName: UIColor.lightGray])
    setUpAgeTextFieldsInputView()
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)

    // Configure the view for the selected state
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let oldLength: Int = (textField.text?.characters.count)!
    let replacementLength: Int = string.characters.count
    let rangeLength: Int
        = Int(range.length)
    let newLength = oldLength - rangeLength + replacementLength
    let returnKey = (string as NSString).range(of: "\n").location != NSNotFound
    return newLength <= maxLength || returnKey
}

func setUpAgeTextFieldsInputView() {
    let inputView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.bounds.width, height: 140))
    
    inputView.backgroundColor = backgroundTint
    
    // setup date picker
    let datePickerView = UIDatePicker(frame: CGRect(x: 0.0, y: 40.0, width: self.bounds.width, height: 100))
    datePickerView.backgroundColor = .clear
    datePickerView.setValue(backgroundTint, forKeyPath: "textColor")
    datePickerView.datePickerMode = UIDatePickerMode.date
    
    // set the date picker max date and showing date
    let gregorian = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
    let currentDate = NSDate()
    let component = NSDateComponents() ; component.year = -18
    let date = gregorian.date(byAdding: component as DateComponents, to: currentDate as Date, options: NSCalendar.Options(rawValue: 0))
    datePickerView.date = date!
    datePickerView.maximumDate = currentDate as Date
    
    inputView.addSubview(datePickerView)
    
    // Make done button
    let doneButton = UIButton(frame: CGRect(x: 0.0, y: 1.0, width: self.bounds.width, height: 38.0))
    doneButton.backgroundColor = UIColor.white.withAlphaComponent(0.1)
    doneButton.setTitle("Done", for: UIControlState.normal)
    doneButton.setTitleColor(appPink, for: UIControlState.normal)
    doneButton.setTitleColor(UIColor.gray, for: UIControlState.highlighted)
    
    inputView.addSubview(doneButton)
    
    // set actions for buttons and picker
    doneButton.addTarget(self, action: #selector(done), for: UIControlEvents.touchUpInside)
    ageTextField.inputView = inputView
    datePickerView.addTarget(self, action: #selector(handleDatePicker(_:)), for: UIControlEvents.valueChanged)
}

func done() {
    self.endEditing(true)
}

func handleDatePicker(_ sender: UIDatePicker) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    ageTextField.text = dateFormatter.string(from: sender.date)
}

}

Upvotes: 1

Views: 12796

Answers (5)

Ganesh G
Ganesh G

Reputation: 2061

This worked for me

datePicker.subviews[0].backgroundColor = .red

Upvotes: 1

Nayan Dave
Nayan Dave

Reputation: 1680

Swift 5+ Answer

picker.setValue(UIColor.lightGray, forKey: "backgroundColor")

Worked For Me !!!

Upvotes: 4

aalesano
aalesano

Reputation: 357

You might want to set UIKeyboardType = .default and UIKeyboardAppearance = .default

Upvotes: 1

sam k
sam k

Reputation: 1107

Hey after going through my code i realised that i had been assigning a keyboard type to my textfield and then i was trying to change its inputview to a datepicker view. removing that assignment fixed my bgcolor issue.

Upvotes: 0

Mundi
Mundi

Reputation: 80271

It seems to be working, only not necessarily in the way you desire.

For example, changing the backgroundColor to something noticeable (other than .clear) apparently works. It changes the tint to that color.

Changing the "textColor" property also produces some noticeable changes, but it seems that the control is dynamically calculating the exact foreground color based on the background in such a way that it is always legible. If you experiment with colors like .ligtGray and .black this will become apparent.

Sorry, for further customization you are out of luck. :(

picker.backgroundColor = .white
picker.setValue(UIColor.red, forKey:"textColor")

Screenshot of date picker

Upvotes: 6

Related Questions