5
votes

I have follow this tutorial and everything works fine. The only issue I'm having is i can't figure out how to detect when a button has been pressed?

Thanks in advance

6
Have you read the documentation? - Daniel Storm
Yes @DanielStorm, I now have a pressesEnded function which never gets called for some reasom - Alex Chesters

6 Answers

6
votes

Author of the tutorial here, the method of adding interactivity to TVML-based apps is to use addEventListener on the DOM element in question. You can find the DOM element by holding a reference to it during creation, or by using getElementById or other such similar JavaScript DOM techniques. Also, I should mention I've added a "Part 2" to the mentioned tutorial which includes this as it's primary focus.

Here's an example of how you might do this in JS, assuming myDOMElement is a variable that references your button as a DOM element.

  myDOMElement.addEventListener("select", function() { alert("CLICK!") }, false);

I have more info on the tutorial of course, so feel free to check that out, too.

2
votes

Button presses are similar to UITouch events. Take a look at the UIPressEvent callbacks in the UIResponder header. UIViewControllers are part of the responder chain, so you can add the callbacks in your view controller similar to this:

- (void)pressesEnded:(NSSet<UIPress *> *)presses withEvent:(nullable UIPressesEvent *)event {

    UIPress *anyPress = [presses anyObject];
    // handle press event

}
2
votes
let playPauseRecognizer = UITapGestureRecognizer(target: self, action: "playPauseRecognizer:")
playPauseRecognizer.allowedPressTypes = [NSNumber(integer:UIPressType.PlayPause.rawValue)]

     view.addGestureRecognizer(playPauseRecognizer)
1
votes

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.

0
votes

You can add action to a UIButton same as iOS, according to Apple Docs

An instance of the UIButton class implements a button on the touch screen. A button intercepts touch events and sends an action message to a target object when tapped. Methods for setting the target and action are inherited from UIControl. This class provides methods for setting the title, image, and other appearance properties of a button. By using these accessors, you can specify a different appearance for each button state.

0
votes

Swift 3 version of @jess-bowers code:

override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
    let anyPress: UIPress? = presses.first
}