#アプリでよく見る長押しして表示するメニュー機能をかんたんに作れる方法です
#わかりやすい長押しポップアップハイライトを作りたいけど、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])
})
}
#アプリづくりのスピードアップ
こういった機能を使うことで、わかりやすいUIを手早く作れるといいですね。
🐣
フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com
Core MLやARKitを使ったアプリを作っています。
機械学習/AR関連の情報を発信しています。