LKM
LKM

Reputation: 2450

How to handle the height of tableviewCell dynamically in iOS?

enter image description here

It's what I made now! I'm newbie for iOS development.

What I want to make is the newsfeed(cardViewUI) like Facebook, but according to my design of cell, when texts are long more than capacity of label(cell's text container), it shows '..' like you see above.

So I want to increase my cell's height dynamically set by length of texts.

I designed it with mainstoryboard not .xib file. I try to [label sizeToFit] and set label's lines to 0 but nothing works so far.

Upvotes: 0

Views: 436

Answers (2)

SGDev
SGDev

Reputation: 2252

Using tableView:heightForRowAtIndexPath: you can give the size of each row at run time. now your problem is how to get height from your string there are function in NSString class by this code your problem,

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  NSString *str = [dataSourceArray objectAtIndex:indexPath.row];
    CGSize size = [str sizeWithFont:[UIFont fontWithName:@"Helvetica" size:17] constrainedToSize:CGSizeMake(280, 999) lineBreakMode:NSLineBreakByWordWrapping];
    NSLog(@"%f",size.height);
    return size.height + 10;
}

by below line you set your labels num. of line to max. so set it incellForRowAtIndexPath:` method.

cell.textLabel.numberOfLines = 0;

if you use some custom cell then manage all label`s string with this and get sum of all that height then set the height of your cell.

Upvotes: 1

DilumN
DilumN

Reputation: 2895

You can calculate the text height as below,

//Height For Row at index path
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellText = [NSString stringWithFormat:@"%@",[arrFullChat[indexPath.row]objectAtIndex:1]];
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:15.0];

    NSAttributedString *attributedText =
    [[NSAttributedString alloc]
     initWithString:cellText
     attributes:@
     {
     NSFontAttributeName: cellFont
     }];
    CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(tableView.bounds.size.width - 90.0, CGFLOAT_MAX)
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    return rect.size.height + 42;
}

42 in this code will be vary to you. Try it with different values.

Don't forget to increase your UITextView height according to the Cell height using Autolayout or any other way you want.

Upvotes: 1

Related Questions