UIButton.addTarget() doesn't register taps on tvOS

Hello guys!


I'm strugling with the following minimal app in tvOS simulator.


I can't make UIButton tap (using Apple TV remote in simulator) to be reported.

I.e. no btnAction() calls. While the same code work as expected in iOS simulator.


Visually everything works as expected in the Apple TV simulator. I can tap the button using the TV Remote controls (in sumulator of course) and I see button press animation. But no btnAction() calls.


Please note that I don't use any storyboard or xib files. Everything is created programatticaly:


import UIKit

class ViewController: UIViewController {


override func viewDidLoad() {

super.viewDidLoad()

addButton("Opt 1", pos: 0, selector: "btnAction:")

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}


func addButton(text: String, pos:CGFloat, selector:Selector? = nil) {


print("addButton \(text)")


let btn:UIButton = UIButton(type: UIButtonType.System)

btn.frame = CGRectMake(30, 30, 300, 100)

btn.setTitle(text, forState: UIControlState.Normal)

view!.addSubview(btn)


if (selector != nil) {

print(" action: \(selector!)")

btn.addTarget(self, action: selector, forControlEvents: UIControlEvents.TouchUpInside)

}

}


func btnAction(btn:UIButton!) {

print("Click!")

}

}



import UIKit

@UIApplicationMain

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {


window = UIWindow(frame: UIScreen.mainScreen().bounds)

window!.makeKeyAndVisible()


let ctrl = ViewController()

window!.rootViewController = ctrl


return true

}

...

}

Accepted Reply

You shouldn't be using "UIControlEvents.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 you wanted here: if you want the Select button press on the remote to trigger your button, you should use PrimaryActionTriggered.

Replies

You shouldn't be using "UIControlEvents.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 you wanted here: if you want the Select button press on the remote to trigger your button, you should use PrimaryActionTriggered.

Thanks a lot, Justin!


Your answer solved the problem that I'd been strugling with for a few hours 🙂 So basically that means that UIControlEvents.PrimaryActionTriggered is the way to go in orger to make tvOS/iOS universal code. It is quite important finding.