Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating attributed string height

Tags:

ios

swift

I'm trying to set a tableViewCell height equal to the height of the attributedString inside the cell. However whatever I do it does not seem to have the correctSize. this is what I've tried so far

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

Customize descLabel in cell subclass

//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

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
    }
}

height Extension

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
    }

}
like image 615
Peter Pik Avatar asked Jan 19 '17 12:01

Peter Pik


Video Answer


1 Answers

You can simply use (the instance of NSAttributedString).size.height

e.g.

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

like image 60
Yuan Fu Avatar answered Oct 07 '22 19:10

Yuan Fu