You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

横向紧凑模式下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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 20:12:18