如何在UILongPressGestureRecognizer iOS Swift 4中传递多个参数?

时间:2018-07-27 06:53:31

标签: ios swift uigesturerecognizer gesture target

我想在iOS Swift 4 *中使用UILongPressGestureRecognizer方法传递一些参数。

let buttonLongGesture = UILongPressGestureRecognizer(target: self, action: #selector(buttonPressedLong(_:)))
button.addGestureRecognizer(buttonLongGesture)

@objc func buttonPressedLong(_ sender:UIGestureRecognizer) {

}

1 个答案:

答案 0 :(得分:3)

我建议您使自定义类继承UI LongPressGestureRecognizer,然后可以在其中添加任何参数作为变量。最后,您可以使用它在手势发生时发送参数。这是一个例子。

class CustomLongPressGesture: UILongPressGestureRecognizer {
    var firstParam: String!
    var secondParam: String!
}

然后您可以像这样实现它:

func setUp() {
    let buttonLongGesture = CustomLongPressGesture(target: self, action: #selector(buttonPressedLong(_:)))
    buttonLongGesture.firstParam = "Test"
    buttonLongGesture.secondParam = "Second Test"
    button.addGestureRecognizer(buttonLongGesture)
}

 @objc func buttonPressedLong(_ sender: CustomLongPressGesture) {
    print(sender.firstParam, sender.secondParam) // Access it here
 }