0

I have string with multiple new line characters like below.

"sdfsdghhfdgdfgfdgdfghjgf
sdfsdfsdfsdfdsfdsfdsgdfgfdhghgfhfgjhf

sdfdsfdsfdsfdsfdsfdsfhhg
sdfsdfdfsd
sdfdsfdsfdsfdsfdfdsfsdf"

Now I am calculating height of label to accommodate above string. Below is my code for it.

label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
label.font = font;
label.text = labelText;

float width = label.frame.size.width;
CGSize jobDescHeightSize = [label sizeThatFits:CGSizeMake(width, CGFLOAT_MAX)];

It gives me correct height in larger device i.e. iPhone XR, iPhone 11 but it doesn't give me correct size of UILabel in iPhone 6s, iPhone 8.

iPhone
  • 4,092
  • 3
  • 34
  • 58

1 Answers1

0

The extension which solved my issue once

extension UILabel{

public var requiredHeight: CGFloat {
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.attributedText = attributedText
    label.sizeToFit()
    return label.frame.height
  }
}

Original Answer

Ankur Lahiry
  • 2,253
  • 1
  • 15
  • 25