# 2.5 菜单与命令


<br>


<br>

Menu 也是一种常用控件，用于创建菜单视图。Button、Toggle、Picker 等常用控件都可以作为 Menu 的子控件，Menu 本身还支持嵌套使用。

<span style="background: #007BFF; color: white; padding: 3px 10px; border-radius: 5px">> 查看示例</span>

Menu 的构建方法中有一个支持 primaryAction 的闭包，没有添加它时，单击 menu 就会弹出菜单，添加之后，单击 menu 的事件就会成为 primaryAction，长按（iOS）或者点击菜单下拉按钮（macOS）时才会弹出菜单。macOS 的下拉菜单按钮可以通过方法 [menuIndicator(_:)](https://developer.apple.com/documentation/swiftui/view/menuindicator(_:)) 隐藏。

[contextMenu](https://developer.apple.com/documentation/swiftui/view/contextmenu(menuitems:)) 可以为视图添加上下文菜单，在 iOS 上通过长按手势唤出菜单，在 macOS 则是点击右键。上下文菜单还支持添加预览，仅在 iOS 上显示。

[Commands](https://developer.apple.com/documentation/swiftui/commands) 主要是为 mac 和 iPad添加命令，这些命令非常适合使用 Menu 进行展示。鉴于 Commands 是 app 的全局行为，难以在单个示例中演示，这里就不一一例举说明了。在 《SwiftUI 中的属性包装器》 中关于 @FocusedBinding 的介绍中，也演示过 [commands(content:)](https://developer.apple.com/documentation/swiftui/scene/commands(content:)) 的使用，它可以为场景新增命令：

```swift
WindowGroup {
  MainWindow()
}
#if os(macOS)
.commands {
  SidebarCommands()
  TestCommands()
}
#endif
```

TestCommands 是之前示例中自定义的 commands，SidebarCommands 是系统内置的命令，添加之后可以通过菜单（*显示 > 隐藏边栏*）或快捷键（⌘ + ⌃ + S）操作 Eul 的边栏显隐。

更多关于菜单与命令的使用，可以参考 [Menus and commands](https://developer.apple.com/documentation/swiftui/menus-and-commands) ，文档中有比较详细的说明和示例，请自行探究和实践。



---

> 作者: 宋明  
> URL: https://apolla.cc/posts/2.5-%E8%8F%9C%E5%8D%95%E4%B8%8E%E5%91%BD%E4%BB%A4/  

