Search code examples
swift3uipickerviewuidatepickeruicontroluicontrolevents

Make a custom class of UIPickerView able to send events in Swift


I've written a custom class based on UIPickerView. Within a class I implemented next method:

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    let min = (selectedRow(inComponent: 0) % minutes.count)
    let sec = (selectedRow(inComponent: 1) % seconds.count)

    self.min = min
    self.sec = sec

    }

Every time user has selected value from "min" and "sec" using picker view, these class variables are changed accordingly. So, it's work ok.

Now, I would like this class to send event every time these variables are changed. Is it possible to adopt valueChanged event for this class, and how to implement it, or I have to make custom event for these purposes? I would like to do it in that way to be able making action outlets via IB. Please, correct me if I missed the pattern.

May be I put this question in other words: what makes the build-in UIDataPicker able to connect to view controller within interface builder with actions outlets - and what should I add to my custom class to achieve partially that functionality?

Apple stated that: "UIDatePicker class uses a custom subclass of UIPickerView to display dates and times." Correct me here if I'm wrong, but they also point out that UIDatePicker inherits from UIControl rather than from UIPickerView. As for UIPickerView - they say it inherits from the UIView. So, I see no connection in terms of inheritance of UIControl for UIPickerView and UIDatePicker. Also I can't inherit UIControl to obtain event sending functionality due to multiple inheritance of UIView class. Can't understand why things here so weird and I can't use UIControl functionality for UIPickerView.


Solution

    1. create YourCustomControl inherit from UIControl
    2. addSubview UIPickerView
    3. set YourCustomControl as a delegate for this picker

    enter image description here

    To send event you need add this line

    sendActions(for: .valueChanged)
    

    in every place where these variables are changed

    UIKit - sendActions