Search code examples
swiftuibuttontvos

Simple tvOS UIButton is not working


I'm trying to implement a simple UIButton (tvOS & Swift), but the TouchDown event isn't firing. (tried also TouchUpInside).

  • In the simulator I can see visually that the button is pressed.

my ViewController.swift code is:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(type: UIButtonType.System)
        button.frame = CGRectMake(100, 100, 400, 150)
        button.backgroundColor = UIColor.greenColor()
        button.setTitle("Test", forState: UIControlState.Normal)
        button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchDown)

        self.view.addSubview(button)

        self.view.userInteractionEnabled = true    
    }

    func buttonAction(sender:UIButton!){
        NSLog("Clicked")
    }
}

What do I need to do in order to detect a button click?


Solution

  • You shouldn't be using ".TouchDown" or ".TouchUpInside" on tvOS, since that doesn't do what you might expect: you probably want to use "UIControlEvents.PrimaryActionTriggered" instead.

    TouchUpInside is triggered by actual touches, which isn't really what happen. If you want the Select button press on the remote to trigger your button, you should use PrimaryActionTriggered.