BobC
BobC

Reputation: 655

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?

Upvotes: 4

Views: 1303

Answers (1)

BobC
BobC

Reputation: 655

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

button.addTarget(self, action: #selector(ViewController.buttonTapped(_:)), for: .primaryActionTriggered)

Upvotes: 8

Related Questions