确定在 XCode / Swift 中点击了哪个 TapGestureRecognizer?

Identifying which TapGestureRecognizer was tapped in XCode / Swift?

我正在尝试做一件简单的事情:我在主故事板上设置了两个矩形视图,然后将它们都包含在 TapGestureRecognizers 中。然后我 link 这些 TGR 到单个 @IBAction 函数。现在我需要以某种方式确定哪一个 TGR 被窃听了。

@IBAction func tapOneAct(sender: AnyObject) {
    println(sender)
}

它尝试使用标签但无法使其工作,显然 TGR 不能被标记? println(sender) 告诉我系统正在运行,但我需要一些可以用于进一步编码的东西,比如标签或其他值。

谢谢帮助!

您可以从情节提要的 Identity Inspector 设置 Restoration ID 视图,然后您的函数将如下所示:

func tapOneAct(sender: UITapGestureRecognizer) {
    if(sender.view!.restorationIdentifier == "view1") // view1 is `Restoration ID` of 1st view
    {
        println("View1 is tapped!")
    }
    if(sender.view!.restorationIdentifier == "view2")// view2 is `Restoration ID` of 2nd view
    {
        println("View2 is tapped!")
    }
}

通过使用 tag 属性 你可以这样做:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var view1: UIView!
    @IBOutlet weak var view2: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let tapGestureView1 = UITapGestureRecognizer(target: self, action: "tapOneAct:")
        let tapGestureView2 = UITapGestureRecognizer(target: self, action: "tapOneAct:")
        //add gesture into both Views.
        view1.addGestureRecognizer(tapGestureView1)
        view2.addGestureRecognizer(tapGestureView2)

    }

    func tapOneAct(sender: UITapGestureRecognizer){

        if let tag = sender.view?.tag {
            switch tag {
            case 1:
                println("First View Tapped")
            case 2:
                println("Second View Tapped")
            default:
                println("Nothing Tapped")
            }
        }

    }
}