0

I have a problem using UILabel. I set the line count as 0. When my label receives a big String as value, occurred line break, the problem is when i will get the height of label, the height comes smaller than it should, only comes the value for a line only, however it is shown the String with two lines.

I have tried to use the code below, but to no avail.

let originalHeight = label.frame.size.height
label.sizeToFit() //or label.layoutIfNeeded()
let newHeight = label.frame.size.height

originalHeight and newHeight is equals.

If the line break is made using the character \n, the above code works.

1 Answers1

1

// MARK: - getting dynamic height of a string

convenience init(for bodyText: String, width: CGFloat) {
if (bodyText.characters.count ?? 0) <= 0 {
    return 0
}
let cellFont = UIFont(name: "Helvetica", size: 15.0)
    //UIFont *cellFont = [UIFont systemFontOfSize:13.f];
var paragraphStyle = NSMutableParagraphStyle.default.mutableCopy()
paragraphStyle.lineSpacing = 1
paragraphStyle.lineHeightMultiple = 1.0
/// Set line break mode
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping
/// Set text alignment
paragraphStyle.alignment = .natural
let attributesDictionary: [AnyHashable: Any] = [
        NSFontAttributeName : cellFont!,
        NSParagraphStyleAttributeName : paragraphStyle
    ]

let expectedLabelSize = bodyText.boundingRect(with: CGSize(width: width, height: FLT_MAX), options: .usesLineFragmentOrigin, attributes: (attributesDictionary as? [String : Any] ?? [String : Any]()), context: nil).size

Objective-C version:

#pragma mark - getting dynamic height of a string
+ (CGFloat)heightForText:(NSString *)bodyText width:(CGFloat)width
{
    if(bodyText.length<=0)
    {
        return 0;
    }

    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:15.0f];

    //UIFont *cellFont = [UIFont systemFontOfSize:13.f];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    [paragraphStyle setLineSpacing:1];
    paragraphStyle.lineHeightMultiple = 1.0f;

    /// Set line break mode
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    /// Set text alignment
    paragraphStyle.alignment = NSTextAlignmentNatural;
    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                      cellFont, NSFontAttributeName,
                                      paragraphStyle,NSParagraphStyleAttributeName,
                                      nil];

    CGSize expectedLabelSize = [bodyText boundingRectWithSize:CGSizeMake(width, FLT_MAX)
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:attributesDictionary
                                                  context:nil].size;
    NSLog(@"height%@",NSStringFromCGSize(expectedLabelSize));
    return expectedLabelSize.height;
}
Dimitar Nestorov
  • 2,411
  • 24
  • 29