You need to enable JavaScript to run this app. UILabel开启自动缩放后富文本自定义段落间距失效问题求解
优惠活动
大模型
产品
解决方案
定价
更多

UILabel开启自动缩放后富文本自定义段落间距失效问题求解

问题描述

我在UILabel中使用了富文本(attributed string),当我开启UILabel的文本自动缩放功能后,自定义的段落间距出现了异常。

设计需求

我期望实现的布局效果如下:
目标布局效果图

实现代码

我参考相关方案实现UILabel的自动缩放功能,代码如下:

let label = UILabel()
label.adjustsFontSizeToFitWidth = true
label.attributedText = attributedString

// 自动缩放仅在富文本设置完成后再设置lineBreakMode时生效,推测富文本设置时会覆盖换行模式等配置
label.lineBreakMode = .byTruncatingTail

当前问题:上述实现没有遵守自定义的段落间距配置,所有内容挤在一起,我设置的paragraphSpacingBefore和paragraphSpacing参数完全被忽略了。

以下是我生成富文本的完整代码:

static func attributedCustomString(topText: String, bottomText: String) -> NSMutableAttributedString {
    let fullString = NSMutableAttributedString()
    
    let mainStringParagraphStyle = NSMutableParagraphStyle()
    mainStringParagraphStyle.alignment = .center
    mainStringParagraphStyle.lineHeightMultiple = 1.4 // 行高倍数,非固定点数值
    
    let mainString = NSAttributedString(string: "\(topText)\n",
                                        attributes: [.paragraphStyle: mainStringParagraphStyle,
                                                     .font: UIFont.systemFont(ofSize: 28)])
    
    fullString.append(mainString)
    
    let lineImageStringParagraphStyle = NSMutableParagraphStyle()
    lineImageStringParagraphStyle.alignment = .center
    lineImageStringParagraphStyle.paragraphSpacingBefore = 24.0 // 图片上方间距
    lineImageStringParagraphStyle.paragraphSpacing = 8.8 // 图片下方间距
    
    let lineImageAttachment = NSTextAttachment(image: #imageLiteral(resourceName: "line-separator"))
    let lineImageString = NSMutableAttributedString(attachment: lineImageAttachment)
    lineImageString.addAttribute(.paragraphStyle,
                                 value: lineImageStringParagraphStyle,
                                 range: NSRange(location: 0, length: lineImageString.length))
    
    let bottomStringParagraphStyle = NSMutableParagraphStyle()
    bottomStringParagraphStyle.alignment = .center
    bottomStringParagraphStyle.lineSpacing = 1.4
    
    let bottomString = NSMutableAttributedString(string: "\n\(bottomText.uppercased())",
                                                 attributes: [.paragraphStyle: bottomStringParagraphStyle,
                                                              .font: UIFont.systemFont(ofSize: 14),
                                                              .foregroundColor: UIColor.white.withAlphaComponent(0.9)])
    bottomString.addAttribute(NSAttributedString.Key.kern, value: 5.0, range: NSRange(location: 0, length: bottomString.length - 1))
    
    fullString.append(lineImageString)
    fullString.append(bottomString)
    
    return fullString
}

请问有什么方案可以同时保留自动缩放功能和自定义段落间距配置?


解决方案

这个问题的根因是UILabel的adjustsFontSizeToFitWidth逻辑仅会自动缩放富文本中的字体尺寸,不会同步调整你设置的固定值段落间距,且多段落混合NSTextAttachment的富文本场景下,系统原生自动缩放逻辑存在缺陷,会直接忽略段落间距配置。

你可以根据业务场景选择以下两种方案解决:

方案1:手动同步缩放段落间距(适合无法拆分的复杂富文本场景)

先计算UILabel实际显示时的字体缩放比例,再遍历富文本的所有段落样式,将所有间距参数按比例调整后重新赋值给UILabel。

示例代码如下:

第一步:新增UILabel分类获取实际缩放比例

extension UILabel {
    /// 计算文本自动缩放的实际比例
    var actualTextScale: CGFloat {
        guard let text = attributedText?.string ?? text, let font = font else { return 1 }
        let originTextWidth = (text as NSString).size(withAttributes: [.font: font]).width
        guard originTextWidth > 0 else { return 1 }
        let scale = bounds.width / originTextWidth
        return min(scale, minimumScaleFactor > 0 ? minimumScaleFactor : 1)
    }
}

第二步:调整富文本段落间距后赋值

let label = UILabel()
label.minimumScaleFactor = 0.5 // 按需设置最小缩放比例
label.adjustsFontSizeToFitWidth = true
let originAttributedString = attributedCustomString(topText: "顶部文本", bottomText: "底部文本")
label.attributedText = originAttributedString
label.lineBreakMode = .byTruncatingTail

// 布局完成后调整段落间距,保证bounds计算准确
label.layoutIfNeeded()
let scale = label.actualTextScale
guard let mutableAttributed = originAttributedString.mutableCopy() as? NSMutableAttributedString else { return }

// 遍历所有段落样式,按比例调整间距
mutableAttributed.enumerateAttribute(
    .paragraphStyle,
    in: NSRange(location: 0, length: mutableAttributed.length),
    options: []
) { value, range, _ in
    guard let originStyle = value as? NSParagraphStyle,
          let mutableStyle = originStyle.mutableCopy() as? NSMutableParagraphStyle else { return }
    mutableStyle.paragraphSpacing *= scale
    mutableStyle.paragraphSpacingBefore *= scale
    mutableStyle.lineSpacing *= scale
    mutableAttributed.addAttribute(.paragraphStyle, value: mutableStyle, range: range)
}

label.attributedText = mutableAttributed

方案2:拆分控件用UIStackView实现(更稳定,优先推荐)

你当前的布局是明显的三段垂直结构:顶部文本、分割线图片、底部文本,完全可以拆分为三个独立控件实现,从根源上规避富文本和自动缩放的兼容问题。

  • 顶部单独使用UILabel显示topText,开启自动缩放
  • 中间使用UIImageView显示分割线图片
  • 底部单独使用UILabel显示bottomText,开启自动缩放
  • 三个控件放入垂直UIStackView中,通过StackView的spacing属性或者自定义约束控制间距,后续调整布局也更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 10:54:04