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

问题描述 投票:0回答:2

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

关于控制台阅读,我不明白为什么绘制整个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)
swift nsmutableattributedstring
2个回答
0
投票

在将标签作为subview添加到视图并设置必要的约束后,您是否尝试过这样做?

我尝试过上述操作,只是将标签固定在视图的中心,然后得到以下结果:(这是很合理的)

txtField.frame: (-1122.0, 359.6666666666667, 2658.0, 17.0)
estimatedFrame: (0.0, 0.0, 2637.017578125, 16.70703125) //The width is less by 20(more or less), like you've specified

0
投票

这是错误的:

paragraphStyle.lineBreakMode = .byTruncatingTail

属性字符串换行与标签换行不同。您的属性字符串需要具有换行符。否则,您仅测量一行的高度。

© www.soinside.com 2019 - 2024. All rights reserved.