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

Xcode 15升级后SwiftUI如何缩小字体行高?原方法已失效

Xcode 15 下缩小 SwiftUI 字体行高的替代方案

在Xcode 15中,._lineHeightMultiple(_:)被标记为内部API后,可通过以下几种方式实现将字体行高缩小至默认值以下:

1. 自定义带行高的Font

通过修改UIFont的描述符,直接创建带有指定行高的SwiftUI Font,这是最原生的解决方案:

extension Font {
    static func customWithLineHeight(name: String, size: CGFloat, lineHeight: CGFloat) -> Font {
        guard let uiFont = UIFont(name: name, size: size) else {
            return .system(size: size)
        }
        let lineHeightRatio = lineHeight / uiFont.pointSize
        let descriptor = uiFont.fontDescriptor.addingAttributes([
            .traits: [UIFontDescriptor.TraitKey.lineHeightMultiple: lineHeightRatio]
        ])
        return Font(UIFont(descriptor: descriptor, size: size))
    }
}

// 使用示例
Text("紧凑行高的示范文本")
    .font(.customWithLineHeight(name: "SF Pro", size: 16, lineHeight: 14))

该方法让字体本身携带行高属性,SwiftUI的Text会自动遵循这个设置,效果稳定。

2. 结合lineSpacing与baselineOffset微调

如果不想自定义字体,可通过负数的lineSpacing缩小行间距,配合baselineOffset调整文本基线,快速实现紧凑排版:

Text("多行文本示例\n第二行内容\n第三行内容")
    .font(.system(size: 16))
    .lineSpacing(-2) // 负数减少行间距
    .baselineOffset(-1) // 调整基线让文本更紧凑

注意:需要根据实际字体大小微调数值,不同字体的适配效果可能有差异。

3. 用UIViewRepresentable包装UILabel

直接复用UIKit中UILabel的行高设置逻辑,适合复杂排版场景:

struct CompactLineHeightText: UIViewRepresentable {
    let text: String
    let font: UIFont
    let lineHeightMultiple: CGFloat

    func makeUIView(context: Context) -> UILabel {
        let label = UILabel()
        label.numberOfLines = 0
        label.lineBreakMode = .byWordWrapping
        return label
    }

    func updateUIView(_ uiView: UILabel, context: Context) {
        let attributedText = NSMutableAttributedString(string: text)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineHeightMultiple = lineHeightMultiple // 小于1则缩小行高
        attributedText.addAttribute(
            .paragraphStyle,
            value: paragraphStyle,
            range: NSRange(location: 0, length: attributedText.length)
        )
        uiView.attributedText = attributedText
        uiView.font = font
    }
}

// 使用示例
CompactLineHeightText(
    text: "需要精准控制行高的文本内容",
    font: .systemFont(ofSize: 16),
    lineHeightMultiple: 0.85
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:17:44