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

SwiftUI 5 Widget中如何让Grid自适应文本避免换行截断?

解决SwiftUI Grid中Widget文本换行截断问题

具体解决方案:

  • 强制文本单行显示:给目标Text添加.lineLimit(1)确保不换行,可选搭配.minimumScaleFactor()应对极端长文本场景,避免截断。
  • 让Grid自适应布局优先级:给Grid设置.layoutPriority(1),让它在Widget布局中优先获取足够空间,同时不挤压其他内容。
  • 移除不必要的约束:确保Text没有固定宽度限制,让其根据内容自动扩展。

修改后的完整代码:

Grid(horizontalSpacing: 4, verticalSpacing: 0) {
    ForEach(Array(dangerRatings.enumerated()), id: \.offset) { index, dangerRating in
        GridRow {
            Color("DangerLevel\(dangerRating.mainValue)")
                .frame(width: 12)
                .clipShape(
                    .rect(
                        topLeadingRadius: index == 0 ? 4 : 0,
                        bottomLeadingRadius: index == dangerRatings.count - 1 ? 4 : 0,
                        bottomTrailingRadius: index == dangerRatings.count - 1 ? 4 : 0,
                        topTrailingRadius: index == 0 ? 4 : 0
                    )
                )
            Text(dangerRating.mainValue)
                .foregroundColor(Color("Text"))
                .bold()
                .lineLimit(1)
        }
        if index < dangerRatings.count - 1 {
            GridRow {
                Color("DangerLevel?").frame(width: 12, height: 3)
                Text("-2300m-")
                    .foregroundColor(Color("Text"))
                    .font(.system(size: 10))
                    .bold()
                    .lineLimit(1)
                    .minimumScaleFactor(0.8)
            }
        }
    }
}
.layoutPriority(1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:52:15