Search code examples
iosswiftuidatepicker

Multiple Date Pickers - Using Value Changed


At the moment I'm adding methods to date pickers to make a change to a variable when the value is changed. Each picker has its own method.

Is there an easy way to combine the methods so I have a single methods which can check which picker was changed, or am I best of having each picker with its own method.

Currently I do

datePickerEnd.addTarget(self, action: #selector(endPickerChange), for: UIControl.Event.valueChanged)
datePickerStart.addTarget(self, action: #selector(startPickerChange), for: UIControl.Event.valueChanged)
datePickerOrdered.addTarget(self, action: #selector(orderedPickerChange), for: UIControl.Event.valueChanged)
datePickerReceived.addTarget(self, action: #selector(receivedPickerChange), for: UIControl.Event.valueChanged)

@objc func endPickerChange () {
    finishedVisible = true
}

@objc func startPickerChange () {
    startedVisible = true
}

@objc func orderedPickerChange () {
    orderedVisible = true
}

@objc func receivedPickerChange () {
    receivedVisible = true
}

Solution

  • Define your picker's value change events like this:

    datePickerEnd.addTarget(self, action: #selector(pickerDidChange), for: UIControl.Event.valueChanged)
    datePickerStart.addTarget(self, action: #selector(pickerDidChange), for: UIControl.Event.valueChanged)
    datePickerOrdered.addTarget(self, action: #selector(pickerDidChange), for: UIControl.Event.valueChanged)
    datePickerReceived.addTarget(self, action: #selector(pickerDidChange), for: UIControl.Event.valueChanged)
    

    Then define the common function like this:

    @objc func pickerDidChange(_ picker: UIDatePicker) {
        switch picker {
            case datePickerEnd: print("datePickerEnd changed")
            case datePickerStart: print("datePickerStart changed")
            case datePickerOrdered: print("datePickerOrdered changed")
            case datePickerReceived: print("datePickerReceived changed")
            default: break
        }
    }