Wednesday, 7 February 2018

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))!
       

No comments:

Post a Comment