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

SwiftUI 如何缩小文本字号使其宽度与上方参考文本完全匹配

问题原因

你之前的写法不生效有两个核心原因:

  1. minimumScaleFactor 必须配合 lineLimit(1) 使用才会触发字号缩小逻辑
  2. 你没有给第二个 Text 限制最大宽度等于上方参考文本的宽度,默认情况下第二个文本会撑满整个父容器的可用宽度,自然不会触发缩放

完整实现方案

通过SwiftUI的PreferenceKey获取参考文本的实际宽度,再将该宽度绑定给第二个文本作为最大可用宽度即可:

// 用于存储参考文本宽度的PreferenceKey
struct ReferenceWidthKey: PreferenceKey {
    static var defaultValue: CGFloat = 0
    static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
        value = nextValue()
    }
}

struct AlignedTextView: View {
    @State private var referenceWidth: CGFloat = 0
    
    var body: some View {
        VStack(alignment: .leading) {
            // 上方参考文本
            Text("A reference text")
                .background(
                    GeometryReader { geo in
                        Color.clear
                            .preference(key: ReferenceWidthKey.self, value: geo.size.width)
                    }
                )
                .onPreferenceChange(ReferenceWidthKey.self) { newWidth in
                    referenceWidth = newWidth
                }
            
            // 需要自适应宽度的文本
            Text("(Adjust the length of this line to match the one above)")
                .lineLimit(1)
                .minimumScaleFactor(0.01)
                .frame(maxWidth: referenceWidth, alignment: .leading)
        }
    }
}

注意事项

  • 如果你的VStack设置的是居中对齐,把第二个Text的frame的alignment参数改为.center即可,和VStack的对齐规则保持一致就不会出现偏移
  • 如果参考文本的内容会动态变化,这套逻辑也能自动同步更新宽度,适配新的参考尺寸

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 12:06:03