0

I have given number of lines to zero for UIlabel so that its height will adjust according its content.

sometimes If I give a big text it grows unto 4 lines in UI but when I access its

frame.size.height

it returns 21 instead of actual height which is way more bigger than that.

Any ideas on how to fix this ?

Rajan M
  • 345
  • 3
  • 22

2 Answers2

1

In your View Controller you can use method which notify you about layout finishing:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("frame = \(label.frame)")
    }
biloshkurskyi.ss
  • 1,358
  • 3
  • 15
  • 34
1

swift

public  static func requiredHeightForLabel(text : String, font : UIFont, width : CGFloat)   -> CGFloat {

    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude))//UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
    label.numberOfLines = 0
    label.lineBreakMode = .byWordWrapping
    label.font = font
    label.text = text

    label.sizeToFit()
    return label.frame.height
}

objective c

+(CGFloat)getLabelHeightForString:(NSString *)string font:(UIFont *)font 
{
CGSize size = CGSizeMake(lablwidth, MAXFLOAT);

NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];

CGSize boundingBox = [string boundingRectWithSize:size

                                          options:NSStringDrawingUsesLineFragmentOrigin

                                       attributes:@{NSFontAttributeName:font}

                                          context:context].size;

size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

return size.width;

}