以编程方式将toTarget动作添加到UIButton

Bob*_*obC 3 uibutton tvos swift3

我测试了大量的样品,但没有一个适合我.这是我的代码:

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.")
}
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Bob*_*obC 6

好吧,按照这个答案,问题就在于此.touchUpInside.在tvOS应该是.primaryActionTriggered.

button.addTarget(self, action: #selector(ViewController.buttonTapped(_:)), for: .primaryActionTriggered)
Run Code Online (Sandbox Code Playgroud)