0
0

More than 1 year has passed since last update.

UIMenuをUIControl (UIView)から呼び出す

Posted at

はじめに

UIMenu iOS13から利用可能なコンテナビューですが、iOS14から UIButtonUIBarButtonItemmenu プロパティが追加されるなど、より簡単に利用できるようになっている印象です。

let sampleMenu = UIMenu(title: "sample menu", children: [
    UIAction(title: "1", handler: { _ in
        // action code
    }),
    UIAction(title: "2", handler: { _ in
        // action code
    }),
    UIAction(title: "3", handler: { _ in
        // action code
    }),

    //...
])

// UIButton
let button = UIButton()
button.menu = sampleMenu

// UIBarButtonItem
let barButton = UIBarButtonItem(systemItem: .action,
                                menu: sampleMenu)

カスタムボタンは、より汎用的に使えるように UIControl などで作成することも少なくないのではと思いますが、残念ながら UIControlmenu プロパティを持ちません。
本記事では、 UIControl (UIView) から UIMenu を呼び出す方法を書き留めておきます。

UIControl にコンテキストメニューを追加する

基本的には公式ドキュメントの手順となります。
https://developer.apple.com/documentation/uikit/uicontrol/adding_context_menus_in_your_app#3698709

UIContextMenuInteraction の追加

let menuButton = UIControl()
let interaction = UIContextMenuInteraction(delegate: self)
menuButton.addInteraction(interaction)

UIControl を長押しすると、アプリはデリゲートにコンテキストメニューを提供するよう求め、 contextMenuInteraction(_:configurationForMenuAtLocation:) を呼び出します。
このままだと、長押ししたときにのみメニューが表示されるので、タップしたときにも表示したい場合には以下の設定を追加します。

menuButton.isContextMenuInteractionEnabled = true
menuButton.showsMenuAsPrimaryAction = true

デフォルトだと isContextMenuInteractionEnabledfalse になっているようで、 ドキュメント によれば UIButtonmenu プロパティを設定するとこちらのプロパティが自動で変更されるとのことですが、 UIControl を利用する場合は手動で設定してあげる必要があります。

contextMenuInteraction で表示したいメニューの設定

override func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
    UIContextMenuConfiguration(identifier: nil,
                               previewProvider: nil,
                               actionProvider: { _ in
        // UIMenuにUIActionを設定する
        UIMenu(title: "",
               options: .displayInline, 
               children: [
            UIAction(title: "menu1") { _ in
                // action code
            },
            UIAction(title: "menu2") { _ in
                // action code
            },
            UIAction(title: "menu3") { _ in
                // action code
            }
        ])
    })
}

以上です。

最後に

UIMenuUIControl から呼び出す方法について書きました。
UIMenu は非常に手軽にメニュー表示できるので、利用できる場面が多いのではないでしょうか。
カスタマイズ性はあまり高くないのですが、軽量に実装したいときには積極的に利用したいです。

参考文献

この記事は、以下の情報を参考に書きました。

0
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
0
0