4
votes

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?

1
Are you able to see the CategoryViewButton when used as the subview? If not it could be a lack of contraint issue.Sethmr
The CategoryViewButton is visible as a sub viewAndrew Walz
It is either something inside of one of your internal classes, or the gesture recognizer doesn't work when being used in a child class. I would try setting up a another gesture recognizer in the child class for the button and see if it is recognized.Sethmr
Make sure the gesture recognizer you are adding is not conflicting with one of it's superviews.Swift Rabbit
I am not adding any explicit gesture recognizers, the code is pretty much it. Is there a way to override if UIKit is adding implicit gesture recognizers to the superview?Andrew Walz

1 Answers

9
votes

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