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

时间:2016-09-07 15:40:18

标签: 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.")
}

我错过了什么?

1 个答案:

答案 0 :(得分:5)

嗯,关注this answer问题出在.touchUpInside上。在tvOS中它应该是.primaryActionTriggered

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