Home > OS >  Tap Gesture not working for custom view in swift
Tap Gesture not working for custom view in swift

Time:07-07

I have a circleButton, and adding a gesture recognizer to it is not working. circleButton is a UIView.

 @IBOutlet private weak var circleButton: UIView!

Here is my code:

class CustomBottomBar: UIView {

@IBOutlet private weak var circleButton: UIView!
@IBOutlet private weak var bottomBarView: UIView!
@IBOutlet private weak var contentView: UIView!


override init(frame: CGRect) {
    super.init(frame: frame)
    commonInit()
}
   
override func layoutSubviews() {
    super.layoutSubviews()
    circleButton.layer.borderColor = UIColor.black.cgColor
    circleButton.layer.borderWidth = 2
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    commonInit()
}

@objc func onAddButtonClicked() {
    print("add")
}

private func commonInit() {
    if let customBar = Bundle.main.loadNibNamed("CustomBottomBar", owner: self, options: nil)?[0] as? UIView {
        customBar.frame = bounds
        addSubview(customBar)
        circleButton.layer.cornerRadius = circleButton.frame.height/2
        circleButton.clipsToBounds = true
        circleButton.isUserInteractionEnabled = true
        print(self.circleButton.frame.size)
        print(self.contentView.frame.size)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onAddButtonClicked))
        circleButton.addGestureRecognizer(tapGesture)
    }
}

}

The frame size is also coming properly for circleButton. Not sure what is the problem. I am using customBottomBar in a storyboard. Here is the full code : https://github.com/hirakjyotiborah/AwesomeTaskManag3r

CodePudding user response:

Inside your Main.storyboard give a height constraint to your bottom Bar as you only set leading , trailing and bottom or do this inside commonInit

// 70 (Bottom bar)   80/2 (half of circle button) = 110
heightAnchor.constraint(equalToConstant: 110).isActive = true

As the base for responding to any click is the frame and the main parent view of the button has zero height

  • Related