Tuesday, December 15, 2015

Setting dynamic height of UILabel / UITextView in iOS

#pragma mark - Set Dyanmic Height of Label and TextView According to Text

//for setting the dynamic height of labels
+(UILabel *)setlableFrame:(UILabel*)myLabel fontSize:(float)size
{
    CGSize possibleSize = [myLabel.text sizeWithFont:[UIFont systemFontOfSize:size]constrainedToSize:CGSizeMake(myLabel.frame.size.width9999)lineBreakMode:NSLineBreakByWordWrapping];
    
    CGRect newFrame = myLabel.frame;
    //myLabel.backgroundColor = [UIColor redColor];
    newFrame.size.height = possibleSize.height;
    //NSLog(@"Height of label %f",newFrame.size.height);
    //NSLog(@"Length of text %lu",(unsigned long)myLabel.text.length);
    myLabel.frame = newFrame;
    return myLabel;
}

//for setting the dynamic height of labels
+(UITextView *)setTextViewFrame:(UITextView*)myLabel fontSize:(float)size
{
    CGSize possibleSize = [myLabel.text sizeWithFont:[UIFont systemFontOfSize:size]constrainedToSize:CGSizeMake(myLabel.frame.size.width9999)lineBreakMode:NSLineBreakByWordWrapping];
    
    CGRect newFrame = myLabel.frame;
    //myLabel.backgroundColor = [UIColor redColor];
    newFrame.size.height = possibleSize.height;
    //NSLog(@"Height of label %f",newFrame.size.height);
    //NSLog(@"Length of text %lu",(unsigned long)myLabel.text.length);
    myLabel.frame = newFrame;
    return myLabel;

}

Note : Just pass the text and font size which is required and get the UILabel / UITextView.

No comments:

Post a Comment