2

I created a custom UIButton with this initialiser :

class CustomButton : UIButton{


override init(frame: CGRect) {
    super.init(frame: frame)
    setUpButtoninClass(frame)

    addTarget(self, action: #selector(handleTap), for:.touchUpInside )

}




fileprivate func setUpButtoninClass(_ frame: CGRect) {
    let padding : CGFloat = 16



    self.frame = frame
    layer.shadowColor = UIColor.darkGray.cgColor
    layer.shadowOpacity = 0.3
    layer.shadowOffset = .zero
    layer.shadowRadius = 10
    layer.cornerRadius = frame.width/2
    backgroundColor = UIColor(white: 0.9, alpha: 1)

    let buttonView = UIView(frame: frame)

    buttonView.layer.cornerRadius = frame.width/2
    buttonView.backgroundColor = .white
    addSubview(buttonView)

    let imageView = UIImageView(image: UIImage(named: "pen")?.withRenderingMode(.alwaysTemplate))
    imageView.tintColor = UIColor(white: 0.7, alpha: 1)
    buttonView.addSubview(imageView)
    imageView.anchor(top: buttonView.topAnchor, leading: buttonView.leadingAnchor, bottom: buttonView.bottomAnchor, trailing: buttonView.trailingAnchor, padding: UIEdgeInsets.init(top: padding, left: padding, bottom: padding, right: padding))

}

@objc func handleTap(){
    print("I'm here")
}


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

}}

In the initialiser I'm adding a target but when I actually initialise the custom button in the VC the #selector method (handleTap) is not called.

This is the implementation of custom Button in VC:

class ViewController: UIViewController {


let circularButton = CustomButton(frame: CGRect(x: 0, y: 0, width: 70, height: 70))


override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addSubview(circularButton)
    circularButton.center = view.center
}

I also tried to add the target when initialising the CustomButton in the VC but nothing changed. I would like to know where I'm making a mistake in setting up the button.

EDIT 1 : this is the Debug View Hierarchy Debug Hierarchy

2 Answers2

1

OMG, after debug your code, buttonView and imageView is on the top. Button is behide. You can set the color to debug it more easily. Delete 2 views above make your code works perfectly

King.lbt
  • 843
  • 5
  • 15
0

I think it's your fault here, Touch is not detected because you added an ImageView to the top of UIButton.
Try this, or this one,

buttonView.isUserInteractionEnabled = true
imageView.isUserInteractionEnabled = true
Baran Gungor
  • 176
  • 8
  • Try this, button.addTarget(self, action: #selector(action(sender:)), for: .touchUpInside). @objc func action(sender: UIButton) { } – Baran Gungor May 18 '20 at 16:42
  • Also with this the button doesn't call the handleTap function –  May 18 '20 at 16:48
  • I solved the problem thanks to the comment of @Rikh under the question –  May 18 '20 at 17:22