How to detect Apple TV Siri Remote button presses?

流过昼夜 提交于 2019-11-30 14:24:18

Apple suggests using a UITapGestureRecognizer to detect when a button is released.

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController {
    UITapGestureRecognizer *tapRecognizer;
}

-(void)viewDidLoad {
    [super viewDidLoad];

    tapRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
    tapRecognizer.allowedPressTypes = @[[NSNumber numberWithInteger:UIPressTypeMenu]];
    [self.view addGestureRecognizer:tapRecognizer];
}

-(void)handleTap:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        NSLog(@"Menu button released");
    }
}

For a complete list of UIPressType's refer to UIPress Class Reference.

You're close! These are the methods you want: they work basically just like the touch equivalents.

- (void)pressesBegan:(NSSet<UIPress *> *)presses withEvent:(UIEvent *)event;
- (void)pressesChanged:(NSSet<UIPress *> *)presses withEvent:(UIEvent *)event;
- (void)pressesEnded:(NSSet<UIPress *> *)presses withEvent:(UIEvent *)event;
- (void)pressesCancelled:(NSSet<UIPress *> *)presses withEvent:(UIEvent *)event;

If you are using something like a UISplitViewController the event detection will happen on the "DetailViewController". But the view controller will still be dismissed! This is to detect that the MENU button was pressed and not override its behaviour.

 override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
    guard let type = presses.first?.type else {
        return
    }

    switch type {
    case UIPressType.Menu :
        //Handle this here
    default : break

    }
}
In Swift 3
override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {

    guard let type = presses.first?.type else {
        return
    }

    switch type {
    case UIPressType.menu : break
    //Handle this here
    default : break

    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!