Tuesday 4 March 2014

set size of UILable with its content text

With my bellow method you can set UILable size with its content text.

-(CGRect)setDynamicHeight:(UILabel *)lbl{
    CGRect myLabelFrame = [lbl frame];
  
    NSString *text = lbl.text;
    CGFloat width = lbl.frame.size.width;
    UIFont *font = lbl.font;
    NSAttributedString *attributedText =
    [[NSAttributedString alloc]
     initWithString:text
     attributes:@
     {
     NSFontAttributeName: font
     }];
    CGRect rect = [attributedText boundingRectWithSize:(CGSize){width, CGFLOAT_MAX}
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;
    
    myLabelFrame.size.height = size.height;
    
    return myLabelFrame;

}

and use this method with my bellow code

    [yourLable setFrame:[self setDynamicHeight:yourLable]];

No comments:

Post a Comment