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
相关产品推荐
相关产品推荐

