Height of UILabel
Sometimes we have to set the large text in UILabel on run time, and we don’t know the number of character. actually when we set the large text in UILabel then we need to increase the UIView height also otherwise it will not scrollable.
for this we need to make the IBOutlet of UILabel and set the properties
a: set no 0f lines – 0
b: not set the height constraints.
c: only set leading, trailing, top or bottom space.
after that, we can set the text into UILabel.
when we set the text in UILabel than we have to increase the height of super view so it becomes scrollable.
for this, we need to find the height of UILabel.
now write the extension in the Global file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
extension String { func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(boundingBox.height) } func width(withConstraintedHeight height: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return ceil(boundingBox.width) } } |
Now you need to pass the width and font size whatever you have set on storyboard just pass it will provide the actual height of UILabel.