Search code examples
iosswiftuibuttonsubview

UIButton can't click after adding subViews


I added a subView to my UIButton that fits it's content, the problem is I can't listen to the action of the button whenever I click it, my guess is because my UIButton is underneath of the subViews that I added, but I don't know how can I resolve it.

This is my code for adding subviews in my button

func setButtonContent(myButtonView: UIButton, textLabel: String, textViewDescription: String) {
    if let nibFile = Bundle.main.loadNibNamed("nibName", owner: self, options: nil)?.first as? FundTransferButton {
        nibFile.frame.size.height = myButtonView.frame.size.height
        nibFile.frame.size.width = myButtonView.frame.size.width
        nibFile.label.text = textLabel
        nibFile.textViewDescription.text = textViewDescription
        myButtonView.addSubview(nibFile)
    }
}

I just want to create a custom button with my custom design in it.


Solution

  • Your immediate problem can be solved by:

    nibFile.isUserInteractionEnabled = false
    

    This makes the subview that you are adding not respond to tap events, so the tap events "go through" the subview and "arrive at" the button.

    If you just want to create a custom UIButton though, you should subclass UIControl or UIButton, and design the button itself in the xib file.