This question already has answers here:
In Swift is there anyway to know which object was swiped?
                                
                                    (2个答案)
                                
                        
                        
                            How to detect which image has been tapped in swift
                                
                                    (1个答案)
                                
                        
                                9个月前关闭。
            
                    
在我的程序中,运行“ newFrees”功能时,它应该激活单击某些标签的功能。根据用户单击的标签,它应该执行不同的操作。我已经到了可以在按下其中一个标签时使它运行一个函数的地步,但是我不知道如何使该函数识别哪个标签调用了它。有什么办法可以确定调用它的标签的名称?

func newFrees() -> Void {

    BM1.isUserInteractionEnabled = true
    BT2.isUserInteractionEnabled = true
    let tap1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
    let tap2 = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
    BM1.addGestureRecognizer(tap1)
    BT2.addGestureRecognizer(tap1)
}


...

@objc func tapFunction(sender:UITapGestureRecognizer) {
    print("tap working")
}


// BM1和BT2是标签。

另外,有没有一种不必使用“ let tap1”和“ let tap2”的方法?每当我将其定义为“ tap”,然后将其添加到BM1和BT2中时,BT2都可以工作,而BM1则不行。

最佳答案

您可以尝试使用这样的标签...。

func newFrees() -> Void {

    BM1.isUserInteractionEnabled = true
    BT2.isUserInteractionEnabled = true
    BTM1.tag = 1
    BTM2.tag = 2
    let tap1 = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
    BM1.addGestureRecognizer(tap1)
    BT2.addGestureRecognizer(tap1)
}

    @objc func tapFunction(sender:UITapGestureRecognizer) {
        print("tap working")
        print("tap working")
        guard let label = sender.view as? UILabel else { return }
        switch label.tag {
        case 1:
            //DO stuff with label 1
        case 2:
            //Do Stuff with label 2
        default:
            break
        }
    }
}

08-05 22:01