Subview Gesture Recognizer not being called

2019-04-10 07:58发布

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条回答
爷的心禁止访问
2楼-- · 2019-04-10 08:01

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

查看更多
登录 后发表回答