8
5

More than 1 year has passed since last update.

え、この機能、デフォルトでUIKitにあったの? 長押しメニュー、Context Menuでかんたんに。

Last updated at Posted at 2022-02-11

#アプリでよく見る長押しして表示するメニュー機能をかんたんに作れる方法です
Feb-11-2022 09-56-15
#わかりやすい長押しポップアップハイライトを作りたいけど、1から作るのはたいへんそう。。。

アプリでよく見るこういう機能、使いたいけど、アニメーションの設定などたいへんそうです。

#すごい便利なUIKitの機能があった
Context Menuは、この機能を短いコードで追加できるものです。

#方法

###UICollectionViewに追加する
CollectionViewにデリゲートメソッドが元々あるので、こちらの方が単一のViewに追加するより楽です。

func collectionView(_ collectionView: UICollectionView,
                    contextMenuConfigurationForItemAt indexPath: IndexPath,
                    point: CGPoint) -> UIContextMenuConfiguration? {
    return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
        let deleteAction = self.deleteAction(indexPath)
        return UIMenu(title: "", children: [deleteAction])
    }
}

これだけでViewがアニメーションでハイライトされ、メニューがポップアップして、背景がぼやけます。
ハプティクスもついています。
もう一度タップすると、選択が解除されます。

メニューの表示位置も、きちんと見えるように自動で調整してくれます。

###UIViewに追加する

let interaction = UIContextMenuInteraction(delegate: self)
view.addInteraction(interaction)

デリゲートメソッドでポップアップメニューの中身を追加します。

func contextMenuInteraction(_ interaction: UIContextMenuInteraction,
                                configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
    return UIContextMenuConfiguration(identifier: nil,
                                      previewProvider: nil,
                                      actionProvider: { suggestedActions in
        let saveAction = UIAction(title: NSLocalizedString("Save", comment: ""),
                                  image: UIImage(systemName: "arrow.down.square")) { action in
                             self.performSave()
                         }
                
        let deleteAction = UIAction(title: NSLocalizedString("Delete", comment: ""),
                                    image: UIImage(systemName: "trash"),
                                    attributes: .destructive) { action in
                               self.performDelete()
                           }
                                            
        return UIMenu(title: "Select Action", children: [inspectAction, deleteAction])
    })
}

Feb-11-2022 10-18-41

#アプリづくりのスピードアップ
こういった機能を使うことで、わかりやすいUIを手早く作れるといいですね。

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLやARKitを使ったアプリを作っています。
機械学習/AR関連の情報を発信しています。

Twitter
Medium

8
5
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
8
5