tap gesture recognizer - which object was tapped?

前端 未结 12 1328
萌比男神i
萌比男神i 2020-12-29 17:47

I\'m new to gesture recognizers so maybe this question sounds silly: I\'m assigning tap gesture recognizers to a bunch of UIViews. In the method is it possible to find out w

12条回答
  •  情书的邮戳
    2020-12-29 18:18

    Swift 5

    In my case I needed access to the UILabel that was clicked, so you could do this inside the gesture recognizer.

    let label:UILabel = gesture.view as! UILabel
    

    The gesture.view property contains the view of what was clicked, you can simply downcast it to what you know it is.

    @IBAction func tapLabel(gesture: UITapGestureRecognizer) {
    
            let label:UILabel = gesture.view as! UILabel
    
            guard let text = label.attributedText?.string else {
                return
            }
    
            print(text)
    }
    

    So you could do something like above for the tapLabel function and in viewDidLoad put...

    Just replace with your actual label name

提交回复
热议问题