横向紧凑模式下SwiftUI Toolbar无法显示溢出项问题
问题描述
在NavigationSplitView的详情视图中添加.toolbar后,在横向紧凑配置(如手机、滑过视图或分屏)下,系统会自动将多余工具栏按钮折叠到上下文菜单,但点击该菜单时无法显示这些折叠项,如何解决这个问题?
代码示例:
import SwiftUI struct ContentView: View { @State var selection: Int? = nil func label() -> Image { Image(systemName: "eye") } var body: some View { NavigationSplitView { List(selection: $selection) { ForEach(0..<10) { item in Text("hey \(item)").id(item) } } } detail: { VStack { Text("Hello, world!") } .padding() .navigationTitle("Woo") .toolbar { ToolbarItem{ Button(action: { }, label: { label() }) } ToolbarItem{ Button(action: { }, label: { label() }) } ToolbarItem{ Button(action: { }, label: { label() }) } ToolbarItem{ Button(action: { }, label: { label() }) } ToolbarItem{ Button(action: { }, label: { label() }) } ToolbarItem{ Button(action: { }, label: { label() }) } } } } }
解决方法
出现这个问题的核心原因是未给ToolbarItem指定明确的布局位置(placement),导致SwiftUI在紧凑布局下无法正确识别哪些按钮需要放入溢出菜单。
你可以通过以下两种方式修复:
方式一:给每个ToolbarItem指定placement
将ToolbarItem的布局位置设置为.primaryAction或.secondaryAction,系统会自动处理溢出逻辑:
.toolbar { ToolbarItem(placement: .primaryAction) { Button(action: { }, label: { label() }) } ToolbarItem(placement: .primaryAction) { Button(action: { }, label: { label() }) } ToolbarItem(placement: .primaryAction) { Button(action: { }, label: { label() }) } ToolbarItem(placement: .primaryAction) { Button(action: { }, label: { label() }) } ToolbarItem(placement: .primaryAction) { Button(action: { }, label: { label() }) } ToolbarItem(placement: .primaryAction) { Button(action: { }, label: { label() }) } }
方式二:使用ToolbarItemGroup统一管理按钮
将多个按钮放入ToolbarItemGroup中,并指定placement,同样能让系统正确处理溢出:
.toolbar { ToolbarItemGroup(placement: .primaryAction) { Button(action: { }, label: { label() }) Button(action: { }, label: { label() }) Button(action: { }, label: { label() }) Button(action: { }, label: { label() }) Button(action: { }, label: { label() }) Button(action: { }, label: { label() }) } }
两种方式都能让紧凑布局下的溢出菜单正常显示所有折叠的工具栏按钮,推荐使用ToolbarItemGroup来简化代码结构。
内容的提问来源于stack exchange,提问作者Warren Burton
相关产品推荐
相关产品推荐

