SwiftUI Text行高调整:_lineHeightMultiple弃用后报错求助
解决SwiftUI Text元素行高过小的问题
可行方案1:利用AttributedString结合自定义字体(iOS 15+)
从iOS 15开始,AttributedString支持通过自定义字体的行高参数控制行高,可替代弃用的_lineHeightMultiple:
struct SmallLineHeightText: View { let text: String let lineHeightMultiple: CGFloat var body: some View { if let font = UIFont.systemFont(ofSize: 17).with(lineHeightMultiple: lineHeightMultiple) { Text(AttributedString(text, attributes: .init([.font: font]))) } else { Text(text) } } } // UIFont扩展,生成指定行高倍数的字体 extension UIFont { func with(lineHeightMultiple: CGFloat) -> UIFont? { let descriptor = fontDescriptor.addingAttributes([ .lineHeightMultiple: lineHeightMultiple ]) return UIFont(descriptor: descriptor, size: pointSize) } }
调用示例:
SmallLineHeightText(text: "Hello world!\nHello world!", lineHeightMultiple: 0.83)
可行方案2:自定义UIViewRepresentable封装UILabel(兼容iOS 13+)
如果需要兼容iOS 13,可调整UILabel的布局逻辑确保和SwiftUI对齐:
struct CustomLineHeightLabel: UIViewRepresentable { let text: String let lineHeightMultiple: CGFloat let fontSize: CGFloat func makeUIView(context: Context) -> UILabel { let label = UILabel() label.numberOfLines = 0 label.lineBreakMode = .byWordWrapping label.baselineAdjustment = .alignBaselines label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) return label } func updateUIView(_ uiView: UILabel, context: Context) { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineHeightMultiple = lineHeightMultiple let attributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: fontSize), .paragraphStyle: paragraphStyle ] uiView.attributedText = NSAttributedString(string: text, attributes: attributes) } }
调用示例:
CustomLineHeightLabel(text: "Hello world!\nHello world!", lineHeightMultiple: 0.83, fontSize: 17) .frame(maxWidth: .infinity, alignment: .leading)
若仍有布局偏移,可在SwiftUI侧添加alignmentGuide对齐基线:
.alignmentGuide(.firstTextBaseline) { $0[.bottom] }
方案说明
- 方案1是iOS 15+的原生解决方案,无需依赖UIKit,布局贴合SwiftUI原生行为。
- 方案2兼容iOS 13+,通过调整UILabel属性和SwiftUI布局参数,可解决之前的布局不符问题。
内容的提问来源于stack exchange,提问作者Nikita Tepliakov
相关产品推荐
相关产品推荐

