Pass extra argument for UItapgestureRecognizer with selector

后端 未结 4 1454
日久生厌
日久生厌 2020-12-11 22:33

I have two labels, Label1 and Label2. I want to make a single function that prints out which label is tapped by creating UITTapRecognizer for both labels calling the same fu

4条回答
  •  再見小時候
    2020-12-11 22:51

    I believe a UITapGestureRecognizer can only be used for a single view. That said, you can have 2 different UITapGestureRecognizers call the same selector and then access the UITapGestureRecognizer in the function. See the following code:

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
    
            super.viewDidLoad()
    
            let label1 = UILabel()
            label1.backgroundColor = UIColor.blueColor()
            label1.frame = CGRectMake(20, 20, 100, 100)
            label1.tag = 1
            label1.userInteractionEnabled = true
            self.view.addSubview(label1)
    
            let label2 = UILabel()
            label2.backgroundColor = UIColor.orangeColor()
            label2.frame = CGRectMake(200, 20, 100, 100)
            label2.tag = 2
            label2.userInteractionEnabled = true
            self.view.addSubview(label2)
    
            let labelOneTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.whichLabelWasTapped(_:)))
            let labelTwoTap = UITapGestureRecognizer(target: self, action: #selector(ViewController.whichLabelWasTapped(_:)))
    
            label1.addGestureRecognizer(labelOneTap)
            label2.addGestureRecognizer(labelTwoTap)
    
    }
    

    Both UITapGestureRecognizers call the same function:

    func whichLabelWasTapped(sender : UITapGestureRecognizer) {
        //print the tag of the clicked view
        print (sender.view!.tag)
    }
    

    If you try to add one of the UITapGestureRecognizers to both labels, then only the last one added will actually call the function.

提交回复
热议问题