如何在SwiftUI for macOS中创建偏好设置样式(图标在上文字在下)的工具栏
原因
macOS 工具栏默认存在高度限制,会自动裁剪超出默认高度的内容,同时 SwiftUI 在 macOS 端的 Button 默认自带内边距和样式约束,会挤压自定义的垂直 Label 布局,导致内容显示不全。
解决方案
- 移除按钮默认样式约束,手动指定适配垂直布局的高度
- 可根据需求调整自定义
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
相关产品推荐
相关产品推荐

