UIButton in Swift is not registering touches UIButton in Swift is not registering touches ios ios

UIButton in Swift is not registering touches


I see it is an old question but I just faced very similar problem yesterday. My buttons were highlighted on touch but not firing the action.

I have two view controllers. One view covers the others view and button is on the top view.

eg.

  • Rootviewcontroller has back view

  • Topviewcontroller has top view

The button on top view does not call the action if I don't add the topviewcontroler as childviewcontroller of the rootviewcontroller. After adding the topviewcontroller as childviewcontroller it started to working.

So in short: just try to add the view controller of buttons superview as childviewcontroller to the parent views viewcontroller with the following method

func addChildViewController(_ childController: UIViewController)


Selectors are a struct that have to be created.

Do it this way...

Updated for Swift 4

settingsButton.addTarget(self, action: #selector(showSettings), for: .touchUpInside)

That should do it.


For anyone else doing manual view layout running into this issue, you might have defined your subview like such:

let settingsButton: UIButton = {    let button = UIButton(type: .system)    // do some more setup    button.addTarget(self, selector: #selector(openSettings), for: .touchUpInside)    return button}()

The error lies with the fact that you are adding a target and passing self before it is actually available.

This can be fixed in two ways

  1. Making the variable lazy and still adding the target in the initialization block:

    lazy var button: UIButton = {    let button = UIButton(type: .system)    // since this variable is lazy, we are guaranteed that self is available    button.addTarget(self, selector: #selector(openSettings), for: .touchUpInside)    return button }()
  2. Adding the target after your parent view has been initialized:

    init() {     self.settingsButton = .init(type: .system)    super.init(frame: .zero)    self.settingsButton.addTarget(self, selector: #selector(openSettings), for: .touchUpInside)}


matomo