2016-09-07 68 views
2

我測試了大量樣本,但沒有一個適合我。這是我的代碼:以編程方式將目標動作添加到UIButton

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

我在想什麼?

回答

4

那麼,在this answer之後問題是.touchUpInside。在tvOS中它應該是.primaryActionTriggered

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