0

I have a bug where sometimes, for certain users, a button press isn't registered.

I have something similar to the following code. This code works fine for me and most people but some of our users don't see anything happen after tapping the button.

class ViewController: UIViewController {
    let nextButton: UIButton = {
        let button = UIButton()
        button.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
        button.setTitleColor(.blue, for: .normal)
        button.setTitle("Button", for: .normal)
        button.addTarget(self, action: #selector(handleButtonPressed(sender:)), for: .touchDown)
        return button
    }()

    @objc fileprivate func handleButtonPressed(sender: UIButton) {
        print("Handle")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(nextButton)
    }
}

Changing nextButton to a lazy var solves the problem for everyone. I assume this is some problem with self not being fully initialized when nextButton is created and that causes the target/selector registration to get messed up.

My question is what could cause this to fail since I can't reproduce the issue myself?

Randall
  • 14,691
  • 7
  • 40
  • 60
  • 1
    Really? You can't reproduce the issue? See [this](https://stackoverflow.com/questions/68205981/what-is-difference-of-self-in-lazy-var-and-varlet-block/68206356). – Sweeper Jul 09 '21 at 08:04
  • I really can't reproduce the issue. The code I posted works as expected. Your answer does shed light on why it wouldn't work, but now I'm confused why the code works for me. – Randall Jul 09 '21 at 08:10
  • What I'm assuming is happening is that the self method is somehow returning nil. Then the button just goes up the responder chain until it finds `handleButtonPressed`. Just need to figure out why that doesn't happen sometimes in my app. – Randall Jul 09 '21 at 08:23
  • 1
    update the action to .touchUpInside – RTXGamer Jul 09 '21 at 09:58
  • 1
    To make it work, either use `lazy` or put `addTarget` in your `viewDidLoad` or `init` method. See this post [can't click UIButton inside a cell in UITableview](https://stackoverflow.com/a/47999822/10158398) too. – Zhou Haibo Aug 06 '21 at 12:43

0 Answers0