ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

swiftui-ui-patterns - menu-bar

2026/10/7 21:18:25 拓冰建站 浏览量
swiftui-ui-patterns - menu-bar 菜单栏Menu Bar意图使用 SwiftUI 命令添加或自定义 macOS/iPadOS 菜单栏时使用。核心模式在Scene级别用.commands { ... }添加命令。UI 包含导航侧边栏时使用SidebarCommands()。对应用特有的菜单使用CommandMenu并对相关操作分组。使用CommandGroup在系统分组之前/之后插入条目或替换它们。对依赖活动场景的上下文相关菜单项使用FocusedValue。示例基础命令菜单mainstructMyApp:App{varbody:someScene{WindowGroup{ContentView()}.commands{CommandMenu(Actions){Button(Run,action:run).keyboardShortcut(R)Button(Stop,action:stop).keyboardShortcut(.)}}}privatefuncrun(){}privatefuncstop(){}}示例插入和替换分组WindowGroup{ContentView()}.commands{CommandGroup(before:.systemServices){Button(Check for Updates){/* open updater */}}CommandGroup(after:.newItem){Button(New from Clipboard){/* create item */}}CommandGroup(replacing:.help){Button(User Manual){/* open docs */}}}示例聚焦的菜单状态ObservablefinalclassDataModel{varitems:[String][]}structContentView:View{StateprivatevarmodelDataModel()varbody:someView{List(model.items,id:\.self){iteminText(item)}.focusedSceneValue(model)}}structItemCommands:Commands{FocusedValue(DataModel.self)privatevarmodel:DataModel?varbody:someCommands{CommandGroup(after:.newItem){Button(New Item){model?.items.append(Untitled)}.disabled(modelnil)}}}菜单栏与设置定义Settings场景会自动在 macOS 上添加设置菜单项。如果需要在应用内使用自定义入口使用OpenSettingsAction或SettingsLink。陷阱避免在多个命令分组中注册相同的键盘快捷键。不要把菜单项作为关键功能的唯一可发现入口。