I know this is an often asked question but I have a specific case of the issue as I abstracted the tapGestureRecognizer so it can be re-used without initialiazing it everytime.
Here is how I use UITapGestureRecognizer on UIlabels :
In UILabel extension :
func setOnClickListener(action: @escaping (_: Any?) -> Void, clickedObject: Any? = nil){
let tapRecogniser = ClickListener(target: self, action: #selector(onViewClicked), clickedObject: clickedObject, onClick: action)
self.addGestureRecognizer(tapRecogniser)
}
@objc func onViewClicked(_ sender: ClickListener) {
sender.onClick?(sender.clickedObject)
}
The ClickListener class :
class ClickListener: UITapGestureRecognizer {
var onClick : ((_: Any?) -> Void)?
var clickedObject: Any?
init(target: Any?, action: Selector?, clickedObject: Any? = nil, onClick: ((_: Any?) -> Void)? = nil) {
self.clickedObject = clickedObject
self.onClick = onClick
super.init(target: target, action: action)
}
}
And here how I call it in my view :
class VoteBoxView: UIView {
private var updateVoteButton: UILabel! = UILabel()
override init(frame: CGRect) {
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initLayout() {
self.addSubview(updateVoteButton)
self.updateVoteButton.text = "Modifier"
self.updateVoteButton.setToSecondaryText()
self.updateVoteButton.setToSecondaryTextColor()
self.updateVoteButton.underline()
self.updateVoteButton.snp.makeConstraints{ (make) -> Void in
make.top.equalTo(self).offset(15)
make.right.equalTo(self)
}
self.initActions()
}
func initActions() {
updateVoteButton.isUserInteractionEnabled = true
updateVoteButton.setOnClickListener(action: updateVote, clickedObject: nil)
}
func updateVote(clickedObject: Any?) {
self.toggleResults(active: false)
}
}
I definitely succeeded to make it work in other cases but there is no differences I can find that would cause it not to work here.
The problem was that I didn't set the correct constraints on my view so the tap was blocked by my ViewController view. I found out by adding colored background on everything.