0
votes

I have a default UIButton linked to an IBAction (touch up inside). This works fine, so I know my connection is OK. Once I change the UIButton class to my custom button, the IBAction is no longer triggered. Below is the code for my custom UIButton. Any ideas why this is happening?

import UIKit

@IBDesignable
class PrimaryButton: UIButton {

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

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


    private func initView() {
        let view = viewFromNibForClass()

        view.frame = bounds

        view.autoresizingMask = [
            UIViewAutoresizing.flexibleWidth,
            UIViewAutoresizing.flexibleHeight
        ]

        addSubview(view)
    }

    private func viewFromNibForClass() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return view
    }
}
2

2 Answers

3
votes

Your code does not work because a button does not receive touches anymore. All touches are sent to the topmost custom view you add.

Set view.userInteractionEnabled = false to make it transparent to touches.

0
votes

Your custom button is covered by the view you added.