How to calculate height of a multiline String in Swift

Calculate Height of text to set dynamic height for complete Text

import UIKit
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: [NSFontAttributeName: font], context: nil)
        return boundingBox.height
    }
}

call this extension in your code
CGFloat TextHeight = (TextLabel.text?.heightWithConstrainedWidth(width:
TextLabel.frame.size.width, font: TextLabel.font))!
       

Comments

Popular posts from this blog

NSPredicate Cheatsheet, Basic, compound, Aggregate, String, comparison operators

what is appDelegate?

CRUD Operation Using RealmSwift database Part 1