1

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?

Anuran Barman
  • 1,556
  • 2
  • 16
  • 31
  • your button is visible bz you are not added the frames – Anbu.Karthik Nov 09 '18 at 12:19
  • sorry, what? did not get you. why do I need a frame? I am adding constraints via code – Anuran Barman Nov 09 '18 at 12:21
  • Yes, You might have auto layout constraints. Can you add your constraints code as well? Also try to set "btnCalibrate?.clipsToBounds = true", it will only show the button visible area. Also check if there is any transparent view on top of your btnCalibrate. – Natarajan Nov 09 '18 at 12:26
  • You are creating a new instance from your button at first line and adding it to your view and last line but you are not adding any frame to it. From other side are you sure that your are working with that instance from line 2 - line 12 ? Maybe there is another global instance – Husein Behboudi Rad Nov 09 '18 at 12:26
  • Yes I am pretty much sure its the same instance being used. and regarding the frame thing, I did add that to my button but that did not work either. – Anuran Barman Nov 09 '18 at 12:44

1 Answers1

0

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)
Daniel Muñoz
  • 547
  • 1
  • 7
  • 23