IRD
IRD

Reputation: 1157

How to increase UILabel hight according to text in UITableView?

I have a custom Cell created for my UITableView. In the .m file of that cell, under

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

I have created a label like this.

self.lblMsg=[[UILabel alloc] initWithFrame:CGRectMake(15.0, self.lblWeatherTitle.frame.origin.y+self.lblWeatherTitle.frame.size.height, size.width-5.0, 50.0)];
    dm.homeMessagelblwidth=size.width-5.0;

    [self.lblMsg setNumberOfLines:0];
    [self.lblMsg setFont:[UIFont systemFontOfSize:15.0]];
    [self.lblMsg setMinimumScaleFactor:12.0];
    [self.lblMsg setLineBreakMode:NSLineBreakByWordWrapping];
    [self.imgvwMSGBG addSubview:self.lblMsg];

The text set from the cellforrowAtIndex delegate in my another viewcontroller class.

That text doesnt have fixed length. What I want to do is change the self.lblMsg and self.imgvwMSGBG hight according to the text. And also I need to increase the row hight under hightForRowAtIndex delegate. How can I increase the label, UIImage and row height according to the text.

Upvotes: 0

Views: 697

Answers (5)

Fahim Parkar
Fahim Parkar

Reputation: 31637

This is what I do.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    int myHt = 100;
    UILabel *commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 100, 1000, 80)];
    if ([localize(@"myLang") isEqualToString:@"en"]) {
        commentLabel.textAlignment = NSTextAlignmentLeft;
    } else {
        commentLabel.textAlignment = NSTextAlignmentRight;
    }
    commentLabel.numberOfLines = 0;
    commentLabel.text = [NSString stringWithFormat:@"%@", [[actualProductsArray objectAtIndex:indexPath.row] valueForKey:@"Comment"]];
    commentLabel.textColor = [UIColor colorWithRed:57/255.0 green:57/255.0 blue:57/255.0 alpha:1.0];
    commentLabel.font = [UIFont fontWithName:localize(@"myFontName") size:40];
    [commentLabel sizeToFit]; // this is very important step

    myHt = myHt + commentLabel.frame.size.height + (10);

    return myHt;
}

Upvotes: 1

sgl0v
sgl0v

Reputation: 1417

The best way would be to use self-sizing cells approach. You should do the next:

1.Set estimatedRowHeight and rowHeight for UITableView:

- (void)viewDidLoad
{
   ...
   self.tableView.estimatedRowHeight = 100.0;
   self.tableView.rowHeight = UITableViewAutomaticDimension;
}

2.Set autolayout constraints for self.lblMsg and self.imgvwMSGBG in the cell's subclass:

UIView *label = self.lblMsg;
UIView *background = self.imgvwMSGBG;
NSDictionary *views = NSDictionaryOfVariableBindings(label, background);

[self.imgvwMSGBG addConstraints:[NSLayoutConstraint 
                constraintsWithVisualFormat:@"V:|-[label]-|"]
                                    options:0
                                    metrics:nil
                                      views:views];
[self.imgvwMSGBG addConstraints:[NSLayoutConstraint 
                constraintsWithVisualFormat:@"H:|-[label]-|"]
                                    options:0
                                    metrics:nil
                                      views:views];

[self.contentView addConstraints:[NSLayoutConstraint 
                constraintsWithVisualFormat:@"V:|-[background]-|"]
                                    options:0
                                    metrics:nil
                                      views:views];
[self.contentView addConstraints:[NSLayoutConstraint 
                constraintsWithVisualFormat:@"H:|-[background]-|"]
                                    options:0
                                    metrics:nil
                                      views:views];

Upvotes: 1

Hitesh Surani
Hitesh Surani

Reputation: 13547

//use this for custom font
CGFloat width =  [label.text sizeWithFont:[UIFont fontWithName:@"ChaparralPro-Bold" size:40 ]].width;

//use this for system font 
CGFloat width =  [label.text sizeWithFont:[UIFont systemFontOfSize:40 ]].width;

label.frame = CGRectMake(point.x, point.y, width,height);

Upvotes: 0

Ankit Sachan
Ankit Sachan

Reputation: 7840

Here goes the method please use proper font and font size

> + (CGFloat) calculateHeight:(NSString *) message withFont:(UIFont *) font withLabelWidth:(CGFloat)width {
>     CGFloat varHeight       =  0;
>     NSString *trimmedString =  [message stringByTrimmingCharactersInSet:[NSCharacterSet
>                                                                     whitespaceAndNewlineCharacterSet]];
>     if(trimmedString.length>0)
>     {
>         CGSize maximumLabelSize     = CGSizeMake(width, 9999);
>         CGRect textRect             = [message boundingRectWithSize:maximumLabelSize options:
>                                        NSStringDrawingUsesLineFragmentOrigin
> attributes:@{NSFontAttributeName:font} context:nil];
>         varHeight                   = ceilf(textRect.size.height);
>     }
>     return varHeight; }

Upvotes: 0

Francis F
Francis F

Reputation: 3285

Try this

-(CGSize)heightForLabelText:(NSString*)labelText withWidth:(float)width andFontSize:(float)size

{

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

    CGSize constraintSize = CGSizeMake(width, MAXFLOAT);

    NSDictionary * attributes = @{NSFontAttributeName:cellFont};

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

    CGRect rect = [labelText boundingRectWithSize:constraintSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:context];

//    NSLog(@"%@ -- (h,w)=(%f,%f)", labelText,rect.size.height,rect.size.width);

    return rect.size;

}
//Usage
    [self heightForLabelText:myLabelText withWidth:300.0 andFontSize:14.0f];

Upvotes: 0

Related Questions