Search code examples
swiftuipickerviewuipickerviewdelegate

Detect when UIPickerView starts changing / moving


I'm trying to react to the event that a UIPickerView started moving (not when the row was already selected).

I have searched throughout the delegate methods, and none helped. I also tried to register a notification, but couldn't figure out any that would notify as the user puts his finger on the component and starts scrolling.

Any ideas of what alternatives are there?


Solution

  • You can create a custom class of UIPickerView and override hitTest(point:with:). Creating a protocol, you can send the current picker through a delegate method to your controller and draw whatever you like:

    protocol CustomPickerViewDelegate: class {
        func didTapped(_ picker: CustomPickerView)
    }
    
    class CustomPickerView: UIPickerView {
    
        weak var myDelegate: CustomPickerViewDelegate?
    
        override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
            // Only test for points in your needed view
            if !self.point(inside: point, with: event) {
                return nil
            }
    
            // Return using CustomPickerViewDelegate the current picker
            // that can be used to determine which one was selected
            myDelegate?.didTapped(self)
    
            // Call super.hitTest(_: with:)
            return super.hitTest(point, with: event)
        }
    }
    

    Do NOT forget (in your controller: eg. YourViewController):

    self.pickerView.myDelegate = self.

    Create an extension of your controller the subscribes to CustomPickerViewDelegate protocol:

    extension YourViewController: CustomPickerViewDelegate {
        func didTapped(_ picker: CustomPickerView) {
            // do what you want here
            self.addBorderTo(picker: picker)
        }
    }
    

    If you like you can extend the UIPickerViewDelegate (see below how you can extend base class delegate)

    Extending a delegate from a base class

    Good luck :]