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()
}
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)
}
You should use enum's rawValue
instead of hash
when you specify allowedPressTypes
:
menuPressRecognizer = [NSNumber(value: UIPressType.menu.rawValue)]
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)}
This can also be done in IB. There's an option on TapGestureRecognizer for buttons which includes the menu button.