4
votes

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?

1

1 Answers

7
votes

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

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