0

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.

Dylan
  • 1,121
  • 1
  • 13
  • 28
  • 1
    I think `nibFile.isUserInteractionEnabled = false` should probably fix it. – Sweeper Feb 21 '20 at 21:20
  • 1
    Does this answer your question? [UIButton with custom view - addTarget:action:forControlEvents: does not work](https://stackoverflow.com/questions/16442559/uibutton-with-custom-view-addtargetactionforcontrolevents-does-not-work) – Kamil.S Feb 21 '20 at 21:22
  • @Sweeper that works for me, thanks! I just get confused because I uncheck the User Interaction Enabled on the root of my xib file in autolayout but nothing happend, i accept that as an answer – Dylan Feb 21 '20 at 21:25

2 Answers2

1

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.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
0

You can add subview layer under your UIButton's layer.

myButtonView.insertSubview(nibFile, at: 0)
urvashi koladiya
  • 168
  • 1
  • 11