Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subview Gesture Recognizer not being called

I am having a problem getting the UITapGestureRecognizer in my custom UIView.to work properly. I Have created a view: CategoryViewButton which adds a UITapGestureRecognizer in the init:

class CategoryViewButton: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap))
    self.addGestureRecognizer(tapGesture)
 }

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
 }

func handleTap() {
    print("Hello again")
 }
}

This gesture recognizer works without issue when added directly in a View Controller. However, when I add a CategoryViewButton as a subview of another custom view, the gesture recognizer method does not get called. My subview:

class CategoryView: UIView, CategoryButtonDelegate {

var button : CategoryViewButton?

override init(frame: CGRect) {
    super.init(frame: frame)
    button = CategoryViewButton(frame: CGRect(x: 10, y: 0, width: 40, height: 25))
    self.addSubview(button!)
    self.bringSubview(toFront: button!)
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
 }
}

When I create a CategoryView in a View Controller, the handleTap() function is not being called. What am I missing?

like image 403
Andrew Walz Avatar asked Jan 06 '23 20:01

Andrew Walz


1 Answers

For anyone curious, the issue was that the subview with gesture recognizer was outside the frame of the superview. This means even though the view was being drawn, the gestures were not detected

like image 134
Andrew Walz Avatar answered Jan 15 '23 18:01

Andrew Walz