LoginSignup
1
0

More than 5 years have passed since last update.

[Swift4]AppleTVでMenuボタンにアクションを追加する方法

Posted at

はじめに

まだまだ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

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0