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

为何将自定义View添加到Toolbar中时Label文本消失?

解决Toolbar中Button仅显示图标不显示文字的问题

问题原因

SwiftUI的Toolbar会根据可用空间自动优化Button的显示样式,当空间有限时(比如iPhone导航栏),默认只保留图标、隐藏文字,这就是你遇到的情况。

解决方法

方法一:强制Label显示标题

给Label添加titleVisibility(.visible)修饰符,强制显示文字,不受空间限制:

struct NewWordButtonView: View {
    @State var isAlert: Bool = false

    var body: some View {
        Button {
            isAlert.toggle()
        } label: {
            Label("change word", systemImage: "arrow.triangle.2.circlepath")
                .fixedSize()
                .titleVisibility(.visible) // 强制显示标题
        }
        .buttonStyle(.bordered)
    }
}

方法二:指定LabelStyle为图标+文字

给Button设置.labelStyle(.titleAndIcon),明确要求同时显示图标和文字:

struct NewWordButtonView: View {
    @State var isAlert: Bool = false

    var body: some View {
        Button {
            isAlert.toggle()
        } label: {
            Label("change word", systemImage: "arrow.triangle.2.circlepath").fixedSize()
        }
        .buttonStyle(.bordered)
        .labelStyle(.titleAndIcon) // 指定显示图标和文字
    }
}

方法三:用HStack手动组合图标和文字

如果上述方法不生效,可以放弃Label,直接用HStack包裹Image和Text,完全自定义Button的内容:

struct NewWordButtonView: View {
    @State var isAlert: Bool = false

    var body: some View {
        Button {
            isAlert.toggle()
        } label: {
            HStack(spacing: 4) {
                Image(systemName: "arrow.triangle.2.circlepath")
                Text("change word")
            }
        }
        .buttonStyle(.bordered)
    }
}

另外,将View加入Toolbar时,确保指定合适的placement(比如.navigationBarTrailing),避免空间被过度压缩:

// 在父View的Toolbar中使用
ToolbarItem(placement: .navigationBarTrailing) {
    NewWordButtonView()
}

内容的提问来源于stack exchange,提问作者Lorenzo Zorri

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:55:32