Bossvanlindt Bossvanlindt - 3 months ago 17
Swift Question

Using didSet to set a NSDate variable when UIDatePicker's date is changed

I am trying to use the didSet property observer to change the (NSDate variable) dueDate's NSDate whenever the UIDatePicker's date is changed in my iOS Swift app. To see if the dueDate was changed accordingly, I want it to display the dueDate on the console. However, my code doesn't do anything at all:

var dueDate = NSDate() {
didSet {
dueDate = datePicker.date
print("\(dueDate)")
}
}


What am I doing wrong?

Answer

It's because you don't seem to observe the UIDatePicker value changes. You should:

1-Add your UIViewController as a target for the ValueChanged event on your UIDatePicker:

datePicker.addTarget(self, action: #selector(ViewController.datePickerValueChanged), forControlEvents: .ValueChanged)

2-When the event is trigged, you have to forward the value to dueDate:

func datePickerValueChanged() {
     self.dueDate = datePicker.date
}

Here is a fully working example:

class ViewController: UIViewController {

    @IBOutlet weak var datePicker: UIDatePicker!

    var dueDate = NSDate() {
        didSet {
            print("New due date value: \(dueDate)")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        datePicker.addTarget(self, action: #selector(ViewController.datePickerValueChanged), forControlEvents: .ValueChanged)

    }
    func datePickerValueChanged() {
        self.dueDate = datePicker.date
    }
}
Comments