检测UIPickerView何时开始更改/移动

时间:2018-11-18 15:50:04

标签: swift uipickerview uipickerviewdelegate

我正在尝试对UIPickerView开始移动的事件做出反应(而不是已经选择该行的情况)。

我搜索了整个委托方法,但没有帮助。我还尝试注册一个通知,但是当用户将手指放在组件上并开始滚动时,找不到能通知的内容。

有什么替代品的想法吗?

1 个答案:

答案 0 :(得分:1)

您可以创建UIPickerView的自定义类并覆盖hitTest(point:with:)。创建协议后,您可以通过委托方法将当前选择器发送到控制器,并绘制所需的内容:

protocol CustomPickerViewDelegate {
    func didTapped(_ picker: CustomPickerView)
}

class CustomPickerView: UIPickerView {

    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)
    }
}

不要忘记(在您的控制器中:例如YourViewController):

self.pickerView.myDelegate = self

为您的控制器创建扩展,以订阅CustomPickerViewDelegate协议:

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

如果愿意,您可以扩展UIPickerViewDelegate(请参见下文如何扩展基类委托)

Extending a delegate from a base class

祝你好运:]