はじめに
SwiftUIのMenu
について、公式ドキュメントを読んだ内容をまとめてみました。
環境
Xcode 14.0
内容
Menu
init(_:content:)
Menu
を使うことで、メニューボタンとメニューオプションを表示することができる
Menu
の中には、さらにMenu
を入れることも可能
Menu("Actions") {
Button("Duplicate", action: duplicate)
Button("Rename", action: rename)
Button("Delete…", action: delete)
Menu("Copy") {
Button("Copy", action: copy)
Button("Copy Formatted", action: copyFormatted)
Button("Copy Library Path", action: copyPath)
}
}
init(content:label:)
Label
を使うこともできる
Menu {
Button("Open in Preview", action: openInPreview)
Button("Save as PDF", action: saveAsPDF)
} label: {
Label("PDF", systemImage: "doc.fill")
}
init(content:label:primaryAction:)
primaryAction
を定義することで、メニューボタンをタップでprimaryAction
の実行、メニューボタンを長押しでメニューオプションが表示されるようになる
Menu {
Button(action: addCurrentTabToReadingList) {
Label("Add to Reading List", systemImage: "eyeglasses")
}
Button(action: bookmarkAll) {
Label("Add Bookmarks for All Tabs", systemImage: "book")
}
Button(action: show) {
Label("Show All Bookmarks", systemImage: "books.vertical")
}
} label: {
Label("Add Bookmark", systemImage: "book")
} primaryAction: {
addBookmark()
}
MenuOrder
menuOrder(_:)
Viewから表示されるMenuの順序を指定する
ContextMenu
contextMenu(menuItems:preview:)
Viewにコンテキストメニューを追加する
Text("Turtle Rock")
.padding()
.contextMenu {
Button {
// Add this item to a list of favorites.
} label: {
Label("Add to Favorites", systemImage: "heart")
}
Button {
// Open Maps and center it on this item.
} label: {
Label("Show in Maps", systemImage: "mappin")
}
}
contextMenu(menuItems:preview:)
Viewにプレビュー付きコンテキストメニューを追加する
Text("Questionmark")
.padding()
.contextMenu {
Button {
// Add this item to a list of favorites.
} label: {
Label("Add to Favorites", systemImage: "heart")
}
Button {
// Open Maps and center it on this item.
} label: {
Label("Show in Maps", systemImage: "mappin")
}
} preview: {
Image(systemName: "questionmark.square.dashed")
.resizable()
.frame(width: 200, height: 200)
}
contextMenu(forSelectionType:menu:primaryAction:)
Viewにアイテムベースのコンテキストメニューを追加する
struct ContextMenuItemExample: View {
var items: [Item]
@State private var selection = Set<Item.ID>()
var body: some View {
List(selection: $selection) {
ForEach(items) { item in
Text(item.name)
}
}
.contextMenu(forSelectionType: Item.ID.self) { items in
if items.isEmpty { // Empty area menu.
Button("New Item") { }
} else if items.count == 1 { // Single item menu.
Button("Copy") { }
Button("Delete", role: .destructive) { }
} else { // Multi-item menu.
Button("Copy") { }
Button("New Folder With Selection") { }
Button("Delete Selected", role: .destructive) { }
}
}
}
}
struct Item: Identifiable {
let id: Int
let name: String
}
- リスト外を長押し
- アイテムを一つ長押し
- アイテムを複数選択して長押し
おわりに
Menu
はよく使っていたましたが、primaryAction
を定義できることは知らなかったので、今回ドキュメントを読んだことで収穫がありました。
参考