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

如何在SwiftUI for macOS中创建偏好设置样式(图标在上文字在下)的工具栏

原因

macOS 工具栏默认存在高度限制,会自动裁剪超出默认高度的内容,同时 SwiftUI 在 macOS 端的 Button 默认自带内边距和样式约束,会挤压自定义的垂直 Label 布局,导致内容显示不全。

解决方案

  1. 移除按钮默认样式约束,手动指定适配垂直布局的高度
  2. 可根据需求调整自定义 VerticalLabelStyle 的间距和字号,适配工具栏尺寸

修正后的核心代码

首先修改工具栏中的按钮部分:

.toolbar {
    ToolbarItem(placement: .principal) {
        Button {
            // 按钮点击逻辑
        } label: {
            Label {
                Text("General")
            } icon: {
                Image(systemName: "gearshape")
            }
            .labelStyle(VerticalLabelStyle())
        }
        .buttonStyle(.plain)
        .frame(height: 45) // 可根据实际布局需求调整数值
    }
}
// 可选:统一调整工具栏整体高度
.toolbarStyle(.unified)
.frame(minHeight: 60, alignment: .center)

可同步调整 VerticalLabelStyle 优化显示效果:

struct VerticalLabelStyle: LabelStyle {
    func makeBody(configuration: Configuration) -> some View {
        VStack(spacing: 4) {
            configuration.icon
                .font(.title2)
            configuration.title
                .font(.caption)
        }
    }
}

修改后即可正常展示图标在上、文字在下的工具栏按钮效果。

内容的提问来源于stack exchange,提问作者Ferdinand Rios

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:36:03