SwiftUI在mac上更改菜单栏远没有storyboard直观,在Swiftui上并没有一个能够控制菜单栏的View文件或者UI的方式来编辑菜单栏,相比storyboard的菜单栏编辑来说,感觉是编程体验的倒退。

那么在swiftUI中如何编辑菜单栏呢?
使用 .commands修饰符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() }.commands { CommandGroup(replacing: .help) { Button(action: {....}) { Text("MyApp Help") } } CommandMenu("Edit") { ... } } } }
|
如何添加链接
我们经常需要在菜单栏中添加一个反馈按钮来通过Safari或者其他浏览跳转到指定的网页。在commands修饰符中似乎无法使用Link组件,那么就需要通过openURL来打开了。
1 2 3 4 5 6 7 8 9
| struct ContentView: View { @Environment(\.openURL) var openURL
var body: some View { Button("Visit Apple") { openURL(URL(string: "https://www.apple.com")!) } } }
|
示例代码
综合两点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| @main struct DelSpace3App: App { @Environment(\.openURL) var openURL var body: some Scene { WindowGroup { ContentView() }.commands { CommandGroup(replacing: .help) { Button(action: { openURL(URL(string: "https://blog.zhheo.com/p/a170ac02.html")!) }) { Text("反馈") } } } } }
|

参考文章
如何在 Safari 中打开网页链接
Main menu in SwiftUI App