在 swift 中向按钮添加手势

Adding gestures to a button in swift

我正在尝试向视图中的现有按钮添加手势(滑动)功能,但我不知道如何将滑动附加到按钮区域。

期望的效果是有一个按钮,我可以按下和滑动来产生不同的结果。到目前为止,我实现手势的方式将它应用于我的整个视图,而不仅仅是按钮。

我觉得它很简单,但我已经逃避了几天 - 我可能只是在寻找错误的东西。

(顺便说一句,我正在将“@IBOutlet var swipeButton: UIButton!”分配给我的按钮)

代码如下:

class ViewController: UIInputViewController {

@IBOutlet var swipeButton: UIButton!

let swipeRec = UISwipeGestureRecognizer()

override func viewDidLoad() {
    super.viewDidLoad()
    self.loadInterface()

    var swipeButtonDown: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "ButtonDown")
    swipeButtonDown.direction = UISwipeGestureRecognizerDirection.Down
    self.view.addGestureRecognizer(swipeButtonDown)
}

@IBAction func buttonPressed(sender: UIButton) {
    var proxy = textDocumentProxy as UITextDocumentProxy
    proxy.insertText("button")
}
func buttonDown(){
    var proxy = textDocumentProxy as UITextDocumentProxy
    proxy.insertText("swipe")
}

}

如果你想在 Button 中添加 swipeGesture,那么可以这样做:

self.yourButton.addGestureRecognizer(swipeButtonDown)

而且您发送的选择器也有错误,应该是这样的:

var swipeButtonDown: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "buttonDown")

ButtonDown更改为buttonDown