计算属性字符串高度

时间:2017-01-19 12:27:49

标签: ios swift

我试图将tableViewCell高度设置为等于单元格内attributedString的高度。但无论我做什么,似乎都没有正确的尺寸。这是我到目前为止所尝试的

cellHeight

//Convert description to NSAttributedString and get height
//width is equal to screen width - right and left offset
//at the end add the bottom and height offset to the cell height
return detailPetViewModel!.description
                .lineSpacing(spacing: 4)
                .heightWithConstrainedWidth(width: Sizes.screenWidth - 40) + 10

在单元子类中自定义descLabel

//Customize descLabel
descLabel.font = FontFamily.Avenir.Regular.font(size: 16)
descLabel.textColor = UIColor(named: .SecondaryTextColor)

//Multiple lines
descLabel.numberOfLines = 0
descLabel.lineBreakMode = .byWordWrapping
descLabel.sizeToFit()

linespacing扩展

extension String {
    func lineSpacing(spacing: CGFloat) -> NSAttributedString {

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = spacing

        let attributedString = NSMutableAttributedString(string: self)
        attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
        return attributedString
    }
}

身高扩展

extension NSAttributedString {
    func heightWithConstrainedWidth(width: CGFloat) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)

        return boundingBox.height
    }

}

2 个答案:

答案 0 :(得分:6)

这是我使用的扩展程序。您不应该传递有关字体或行高的任何信息,因为属性字符串已知道其值。

extension NSAttributedString {

func height(containerWidth: CGFloat) -> CGFloat {
    let rect = self.boundingRect(with: CGSize.init(width: containerWidth, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
    return ceil(rect.size.height)
}

func width(containerHeight: CGFloat) -> CGFloat {
    let rect = self.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: containerHeight), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
    return ceil(rect.size.width)
}

}

像这样使用:

let height = detailPetViewModel!.description.height(containerWidth: Sizes.screenWidth - 40 + 10)

答案 1 :(得分:-1)

您可以简单地使用(the instance of NSAttributedString).size.height

例如

let a = NSAttributedString(string: "A string", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14)])
let height = a.size().height