How to handle Menu Button action in tvOS remote

2019-07-18 08:41发布

问题:

I am facing the strange problem with my application. Actually when i am presenting a view controller for play the video. At the video load time user press the menu button the application goes to background. While i have overwrite the Menu Button Action.

This is my code.

override func viewWillAppear(animated: Bool) {
    let menuPressRecognizer = UITapGestureRecognizer()
    menuPressRecognizer.addTarget(self, action: #selector(VideoPlayerViewController.menuButtonAction(_:)))
    menuPressRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.Menu.hashValue)]
    self.playerController.view.addGestureRecognizer(menuPressRecognizer)
}

func menuButtonAction(ges:UITapGestureRecognizer) {
    self.dismissView()
 }

回答1:

This is my code and working for me.

Swift 3

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let menuPressRecognizer = UITapGestureRecognizer()
    menuPressRecognizer.addTarget(self, action: #selector(YourViewController.menuButtonAction(recognizer:)))
    menuPressRecognizer.allowedPressTypes = [NSNumber(value: UIPressType.menu.rawValue)]
    self.view.addGestureRecognizer(menuPressRecognizer)
}

func menuButtonAction(recognizer:UITapGestureRecognizer) {
    self.dismiss(animated: true, completion: nil)
}

Swift 4

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let menuPressRecognizer = UITapGestureRecognizer()
    menuPressRecognizer.addTarget(self, action: #selector(YourViewController.menuButtonAction(recognizer:)))
    menuPressRecognizer.allowedPressTypes = [NSNumber(value: UIPressType.menu.rawValue)]
    self.view.addGestureRecognizer(menuPressRecognizer)
}

@objc func menuButtonAction(recognizer:UITapGestureRecognizer) {
    self.dismiss(animated: true, completion: nil)
}

Swift 4.2 & 5

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let menuPressRecognizer = UITapGestureRecognizer()
    menuPressRecognizer.addTarget(self, action: #selector(YourViewController.menuButtonAction(recognizer:)))
    menuPressRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.menu.rawValue)]
    self.view.addGestureRecognizer(menuPressRecognizer)
}

@objc func menuButtonAction(recognizer:UITapGestureRecognizer) {
    self.dismiss(animated: true, completion: nil)
}


回答2:

You should use enum's rawValue instead of hash when you specify allowedPressTypes:

menuPressRecognizer = [NSNumber(value: UIPressType.menu.rawValue)]



回答3:

When you want to multiple add multiple values you can do simple:

let pressTypes: [NSNumber] = [UIPressType.select, UIPressType.playPause, UIPressType.rightArrow].map{ NSNumber(value: $0.rawValue)}


回答4:

This can also be done in IB. There's an option on TapGestureRecognizer for buttons which includes the menu button.