2

我的用户界面上有多个按钮,我想根据不同类型的点击执行不同的功能,

  • 单击
  • 双击
  • 长按

单击一次对我来说很容易,一个连接了所有四个按钮的 IBAction,但是对于其他类型的点击,我被卡住了,

我知道我需要使用点击手势识别器,但我无法将其设置为多个 UIButtons,

这是我想做的例子

import UIKit

class ViewController: UIViewController {


@IBOutlet weak var Label: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


func ButtonSingleTap(sender:UIButton!) {

    let ButtonNumber: String = String(sender.tag)
    Label.text = "Button " + ButtonNumber + " is Single Tapped"
}


func ButtonDoubleTap(sender:UIButton!) {

    let ButtonNumber: String = String(sender.tag)
    Label.text = "Button " + ButtonNumber + " is Double Tapped"
}


func ButtonLongTap(sender:UIButton!) {

    let ButtonNumber: String = String(sender.tag)
    Label.text = "Button " + ButtonNumber + " is Long Pressed"
}
}

用户界面界面

4

1 回答 1

6

您不能将一个实例UIGestureRecognizer用于多个按钮。每个按钮都需要自己的一组手势识别器。

这是一个示例,向您展示如何做到这一点:

for button in [button1, button2, button3, button4] {
    let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: Selector("didLongPress:"))
    let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: Selector("didDoubleTap:"))
    doubleTapRecognizer.numberOfTapsRequired = 2
    button.addGestureRecognizer(longPressRecognizer)
    button.addGestureRecognizer(doubleTapRecognizer)
}

func didLongPress(recognizer: UILongPressGestureRecognizer) {
    guard let button = recognizer.view as? UIButton else { return }
    switch recognizer.state {
    case .Began:
        print("long press began button \(button.tag)")
    case .Ended:
        print("long press ended button \(button.tag)")
    default:
        break
    }
}

func didDoubleTap(recognizer: UITapGestureRecognizer) {
    guard let button = recognizer.view as? UIButton else { return }
    print("double tap button \(button.tag)")
}

为此,您必须为按钮添加 Outlets ( button1, button2, button3, button4)。

于 2015-10-28T17:57:27.690 回答