【SwiftUI】Menuについて

今回は、iOS14で追加されたMenuについてとりあげます。
Appleの公式ドキュメントにあった例を試してみました。デザイン変更も試してみましたが、2021年4月時点メニュー内は変更が難しいようです。利用用途として、シンプルなメニューの表示として利用が良さそうです。
・Apple Document Menu
https://developer.apple.com/documentation/swiftui/menu

動画とコードを掲載します。

動画の画面上にプラスマークのアイコンと「Create」テキストで動作するメニューと「Action」というテキストで表示するメニューを2種類表示させてます。「Action」というテキストのメニューは、メニュー内のCopyという項目を押下した場合、更に、メニューが表示されています。

struct ContentView: View {
var body: some View {
VStack(spacing: 50.0){
//ex1)
Menu {
Button("Cancel", action: {})
Button("Search", action: {})
Button("Add", action: {})
} label: {
Label("Create", systemImage: "plus.circle")
}
//ex2)
Menu("Actions") {
Button("Duplicate", action: {})
Button("Rename", action: {})
Button("Delete…", action: {})
Menu("Copy") {
Button("Copy", action: {})
Button("Copy Formatted", action: {})
Button("Copy Library Path", action: {})
}
}
}
}
}

・今後の課題
メニューの中のデザインを変更しよう試みましたが、うまくいきませんでした。試した内容は、以下の図で、「Create customStyle」というメニューを出すボタンのデザインの変更と、「Create customStyle」を押下後に出てくるメニューです。「Create customStyle」のみ変更されました。メニュー内のデザインの変更方法は、今後の課題としております。試した時のコードも記載します。
struct ContentView: View {
var body: some View {
Menu {
Button("Cancel", action: {}).background(Color.green)// not work
Button("Search", action: {}).overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(Color.blue, lineWidth: 1)
)//not work
Button(action: {}){
Text("Action")
.background(Color.green)
}//not work
} label: {
Label("Create customStyle", systemImage: "plus.circle")
}.menuStyle(CustomMenu()) // work
}
}
struct CustomMenu: MenuStyle {
func makeBody(configuration: Configuration) -> some View {
Menu(configuration)
.padding(10.0)
.background(Color.yellow)
.foregroundColor(.red)
.cornerRadius(10.0)
.clipped()
}
}

・追加:できたこと
追加の確認でメニュー内のアイコンは表示できました。以下は、コードと画面表示になります。
struct ContentView: View {
var body: some View {
VStack(spacing: 50.0){
Menu {
Button("Cancel", action: {})
//image 追加
Button(action: {}) {
Text("Share")
Image(systemName: "square.and.arrow.up")
}
Button("Add", action: {})
} label: {
Label("Create", systemImage: "plus.circle")
}
}
}
}

このブログの人気の投稿

アプリアイコンの素材探し

【SwiftUI】グラスモーフィズムを試してみました

【SwiftUI】LazyVGridについて