如何获取绘制 NSMutableAttributedString 所需的矩形的估计大小?

How to get the estimated size of a rectangle required to draw NSMutableAttributedString?

我正在尝试获取绘制 NSMutableAttributedString 所需的矩形的估计大小。不来的数字对我来说没有任何意义。我有一个带有 UIlabel (txtField) 的 UIViewController,带有 UIlabel.numberOfLines = 3。如果我设置 UIlabel.numberOfLines= 0.

,我想估计这个 NSMutableAttributedString 的高度

参考控制台读数,我不明白为什么绘制整个 NSMutableAttributedString 所需的矩形估计高度小于如果仅限制为 3 行?

var txtField: UILabel = {
    let label = UILabel()
    label.numberOfLines = 3
    label.translatesAutoresizingMaskIntoConstraints = false
    label.lineBreakMode = .byTruncatingTail
    return label
}()


override func viewDidLoad() {
    super.viewDidLoad()

    let content = "Pasture he invited mr company shyness. But when shot real her. Chamber her 
     observe visited removal six sending himself boy. At exquisite existence if an oh dependent excellent. Are gay head need down draw. Misery wonder enable mutual get set oppose the uneasy. End why melancholy estimating her had indulgence middletons. Say ferrars demands besides her address. Blind going you merit few fancy their. "

    let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14)]
    let attributedString = NSMutableAttributedString.init(string: content, attributes: attributes)

    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.lineSpacing = 1.5
    paragraphStyle.lineBreakMode = .byTruncatingTail
    attributedString.addAttributes([.paragraphStyle : paragraphStyle], range: NSRange(location: 0, length: attributedString.length))
    txtField.attributedText = attributedString

}


override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let attText = txtField.attributedText{
        let size = CGSize.init(width: txtField.frame.width - 20, height: 1000)
        let estimatedFrame = attText.boundingRect(with: size, options: .usesLineFragmentOrigin, context: nil)
        print("txtField.frame: \(txtField.frame)")
        print("estimatedFrame: \(estimatedFrame)")

    }
}

控制台:

txtField.frame: (0.0, 0.0, 394.0, 53.333333333333336)
estimatedFrame: (0.0, 0.0, 367.28125, 16.70703125)

这是错误的:

paragraphStyle.lineBreakMode = .byTruncatingTail

属性字符串换行不同于标签换行。您的属性字符串需要具有换行符模式。否则你测量的只是一条线的高度。