はじめに
まだまだtvOSの情報(日本語とか特に)がころがっていない2018年の年末に近づいてきました。
今回はSwift4でtvOSのApple TV Remoteの「Menu」ボタンにアクションを加える方法について記述します。
さっとググればstack overflowなどでソリューションを見つけられるので、既にググった上でここに辿り着いた方は見新しいものはないのでお引取りください..
UITapGestureRecognizerを用いる
ViewController.swift
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let menuPressRecognizer = UITapGestureRecognizer()
menuPressRecognizer.addTarget(self, action: #selector(ViewController.menuButtonAction(recognizer:)))
// UIPress.PressType.menu.hashValue ではなくUIPress.PressType.menu.rawValue
menuPressRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.menu.rawValue)]
self.view.addGestureRecognizer(menuPressRecognizer)
}
func menuButtonAction(recognizer:UITapGestureRecognizer) {
// ここにアクションを追加
self.dismiss(animated: true, completion: nil)
}
}
ポイント
- .rawValue
Stack OverflowなどでmenuPressRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.menu.hashValue)]
と書いてあるものがありますが、.rawValue
で動作します。
参考サイト
https://stackoverflow.com/questions/40634638/how-to-handle-menu-button-action-in-tvos-remote/41426885
https://qiita.com/noppefoxwolf/items/d2d6389127089f737a1b