Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically addTarget action to UIButton

I tested a ton of samples but none of them works for me. Here is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton(frame: CGRect(x: 100, y: 100, width: 200, height: 50))
    button.backgroundColor = .green
    button.setTitle("Test Button", for: .normal)
    button.titleLabel?.sizeToFit()
    button.addTarget(self, action: #selector(ViewController.buttonTapped(_:)), for: .touchUpInside)

    self.view.addSubview(button)
}

func buttonTapped(_ sender: UIButton) {
    print("Button tapped.")
}

What am I missing?

like image 299
BobC Avatar asked Mar 12 '23 04:03

BobC


1 Answers

Well, following this answer the issue is with .touchUpInside. In tvOS it should be .primaryActionTriggered.

button.addTarget(self, action: #selector(ViewController.buttonTapped(_:)), for: .primaryActionTriggered)
like image 102
BobC Avatar answered Mar 28 '23 23:03

BobC