【问题标题】:Getting UILabel Height by giving String, UIFont and Number of lines通过给出字符串、UIFont 和行数来获取 UILabel 高度
【发布时间】:2020-03-03 16:18:29
【问题描述】:

我找到了几个关于如何使用给定文本和 UIFont 计算 UILabel 高度的好答案:

extension String {
    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedStringKey.font: font], context: nil)
        return boundingBox.height
    }
}

但是,我想更进一步,用给定的文本、字体和行数计算高度。这甚至可能吗?所以,如果高度应该是 2 行,我想要 2 行的高度。

谢谢。

【问题讨论】:

标签: swift


【解决方案1】:

在 Swift 5 中:

Rob 为我指出了正确的方向,我看到可以通过使用 UIFont.lineHeight 来实现行数。

在给定文本、宽度和最大行数的情况下获得正确高度的解决方案。

func height(width: CGFloat, font: UIFont, maxLines: CGFloat = 0) -> CGFloat {
    //Calculating height
    let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
    let boundingBox = self.boundingRect(with: constraintRect,
                                        options: [.usesLineFragmentOrigin, .usesFontLeading],
                                        attributes: [NSAttributedStringKey.font: font], context: nil)

    let height = ceil(boundingBox.height)
    if maxLines > 0 {
        let lines = height / font.lineHeight

        if lines >= maxLines {
            return (boundingBox.height / lines) * maxLines
        }

    }

    return height
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2018-07-09
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多