spoax
spoax

Reputation: 589

Add gesture to UILabel

I am trying to add a tap gesture to my UILabel but cant get it to pop up when tapping on the label. I have had a look to see how everyone else was doing it and from the ones I have found they have been declaring the label in one line then adding the gesture inside view did load. Is it possible to add the gesture inside my label declaration to keep it tidy?

let apetureButton: UILabel = {
    let tapLabel = UITapGestureRecognizer(target: self, action: #selector(apetureSelect))
    let text = UILabel() 
    text.isUserInteractionEnabled = true
    text.addGestureRecognizer(tapLabel)
    text.text = "400"  
    return text
}()

@objc func apetureSelect(sender:UITapGestureRecognizer) {
     print("ApetureSelect")
}

Upvotes: 1

Views: 244

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You need a lazy var to be able to access self from inside the closure

lazy var apetureButton: UILabel = { 
   let text = UILabel() 
   let tapLabel = UITapGestureRecognizer(target: self, action: #selector(apetureSelect))
   text.isUserInteractionEnabled = true
   text.addGestureRecognizer(tapLabel)
   text.text = "400" 
   return text
}()

Upvotes: 3

Related Questions