UIButton Image is not clickable

860 views Asked by At

I am trying to add Image to my MDCRaisedButton which is an extended class from UIButton for MaterialComponents from Google. I am able to add the image to the button but the image is not clickable. I have tried both adding UITapGestureRecognizer and addTarget but the problem persists for both of them. Fact is the image itself is not clickable but if I click the smaller portion of the button remaining below and above the image the button's click action is taken. What can be wrong with this? Below is my code for the button

        btnCalibrate = MDCRaisedButton()
        btnCalibrate?.setImage(UIImage(named: "chip"), for: .normal)
        btnCalibrate?.backgroundColor = UIColor(netHex: Constants.color)
        btnCalibrate?.layer.cornerRadius = 40.0
        btnCalibrate?.imageEdgeInsets=UIEdgeInsets(top: 5, left: 2, bottom: 5, right: 2)
        btnCalibrate?.imageView?.contentMode = .scaleAspectFit
        btnCalibrate?.isUserInteractionEnabled=true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(recalibrateFromImageView(_:)))
        btnCalibrate?.addGestureRecognizer(tapGesture)

        btnCalibrate?.translatesAutoresizingMaskIntoConstraints=false
        //btnCalibrate?.addTarget(self, action: #selector(recalibrate(_:)), for: [.touchUpInside])

        self.addSubview(btnCalibrate!)

I have also tried adding the gesture recognizer to the imageView of the UIButton but that too is not working.

The image is currently coming as centered. If I click the other visible portions of the button which is hardly clickable. How can I handle this?

1

There are 1 answers

0
Daniel Muñoz On

try with

let plusImage = UIImage(named: "chip").withRenderingMode(.alwaysTemplate)
btnCalibrate.setImage(plusImage, for: .normal)

or

let plusImage = UIImage(named: "chip").withRenderingMode(.alwaysTemplate)
btnCalibrate.setBackgroundImage(plusImage, for: .normal)