SwiftUI中如何避免特定字体的文本顶部被截断?
SwiftUI 特定字体文本顶部截断问题解决方案
在SwiftUI开发中,使用以下代码展示时间文本时,选用Academy Engraved LET、Rockwell这类特定字体,会出现文本顶部被截断的情况:
ZStack { Rectangle() .fill(.yellow) .frame(width: 150, height: 150) .cornerRadius(10) .shadow(radius: 3, x: 1, y: 1) .padding(.vertical, 5) VStack(spacing: 0) { Text(Date(), style: .time) .font(.custom(font.code, size: 28)) .bold() .foregroundColor(textColor) .padding(.top, 10) .padding(.bottom, 3) Spacer() } .frame(width: 150, height: 150) }
注:只需在.custom()方法中传入Academy Engraved LET或Rockwell的字体标识符即可复现问题。
可行的解决办法
增大顶部内边距或行间距
这类字体的字形结构通常有较大的顶部延伸,默认内边距不足以容纳。直接调整顶部padding值,或添加行间距来预留空间:Text(Date(), style: .time) .font(.custom("Academy Engraved LET", size: 28)) .bold() .foregroundColor(textColor) .padding(.top, 12) // 增大顶部内边距 .lineSpacing(4) // 额外增加行间距 .padding(.bottom, 3)结合
fixedSize强制文本完整显示
给文本添加上下内边距后,用fixedSize()避免父容器的约束挤压文本:Text(Date(), style: .time) .font(.custom("Rockwell", size: 28)) .bold() .foregroundColor(textColor) .padding(.vertical, 8) .fixedSize()给文本单独设置足够的frame高度
手动指定文本的显示高度,确保字形有足够空间展开:VStack(spacing: 0) { Text(Date(), style: .time) .font(.custom("Academy Engraved LET", size: 28)) .bold() .foregroundColor(textColor) .frame(height: 40) // 预留足够高度 .padding(.top, 8) Spacer() } .frame(width: 150, height: 150)基于字体度量动态调整内边距
通过UIFont获取字体的上升高度(ascender)等度量数据,动态计算需要的顶部内边距,适配不同字体:if let uiFont = UIFont(name: "Rockwell", size: 28)?.bold() { // 计算超出capHeight的顶部额外高度 let extraTopPadding = uiFont.ascender - uiFont.capHeight Text(Date(), style: .time) .font(Font(uiFont)) .foregroundColor(textColor) .padding(.top, 10 + extraTopPadding) .padding(.bottom, 3) }
内容的提问来源于stack exchange,提问作者erotsppa
相关产品推荐
相关产品推荐

