Swift, Custom UIButton does not work when click

kakajan picture kakajan · Feb 10, 2016 · Viewed 14.2k times · Source

I have a custom UIButton created with xib file. When i use my custom button on my view, it does not work when i press to it.

My RoundBtn.swift file:

import UIKit

@IBDesignable class RoundBtn: UIButton {

    var nibName = "RoundBtn"

    @IBOutlet weak var btnImageView: UIImageView!
    @IBOutlet weak var btnLabel: UILabel!

    @IBInspectable var image: UIImage? {
        get {
            return btnImageView.image
        } set(image) {
            btnImageView.image = image
        }
    }

    @IBInspectable var label: String? {
        get {
            return btnLabel.text
        } set(label) {
            btnLabel.text = label
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

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

    func setup() {
        let view = loadViewFromNib()
        view.frame = self.bounds
        view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
        btnImageView.layer.cornerRadius = 60/2
        btnImageView.layer.borderColor = UIColor(red: 5/255,
            green: 66/255, blue: 38/255, alpha: 1).CGColor
        btnImageView.layer.borderWidth = 2
        btnLabel.font = UIFont.boldSystemFontOfSize(14.0)
        btnImageView.userInteractionEnabled = true
        btnLabel.userInteractionEnabled = true
        view.userInteractionEnabled = true
        addSubview(view)
    }

    func loadViewFromNib() -> UIButton {
        let bundle = NSBundle(forClass: self.dynamicType)
        let nib = UINib(nibName: nibName, bundle: bundle)
        let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIButton   
        return view
    }   
}

My RoundBtn.xib file:

enter image description here

View where i used my custom button:

enter image description here

I enabled userInteractionEnabled on all view components. When i click to my custom button, it does not work. I tried by defining on click programmatically and by defining action segue (show).

@IBAction func myCartBtnPressed(sender: AnyObject) {
    print("my cart btn pressed")
}

Answer

fdiaz picture fdiaz · Feb 10, 2016

I think this is caused because you're adding a couple of UIViews subviews to your current UIButton with userInteractionEnabled, which means that they're handling the user input.

If you do:

view.isUserInteractionEnabled = false

The RoundBtn itself will get all the touch events, instead of this UIViews that you have on top.