Edward Edward - 1 year ago 77
Objective-C Question

Dynamic custom UITableViewCell's height based on label text length

I'm noob in Xcode and Objective-C and I need help to make a dynamic table view cell's height based oh how many character in the label. So it will be like this:
if textLabel char is more than 10 it will resize the listHeight to 50
else if textLabel char is more than 20 it will resize the listHeight to 70
and so on...

This is how i code:

NSLong *text;

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
static NSString *cellID = @"ChatTableViewCell";
ChatTableViewCell *cell = (ChatTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellID];

if (cell == nil){
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ChatTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];

Chat * chatObject;
chatObject = [chatArray objectAtIndex:indexPath.row];
cell.nameChat.text = chatObject.name;
cell.messageChat.text = chatObject.message;
cell.messageChat.lineBreakMode = UILineBreakModeTailTruncation;
cell.messageChat.numberOfLines = 0;
cell.dateChat.text = chatObject.time_entry;

//attached foto
NSString *setPhoto=chatObject.photo;
[cell.imageChat setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost/summit/www/media/user/photo/%@",setPhoto]]]]];
cell.imageChat.layer.cornerRadius=cell.imageChat.frame.size.height /2;;
cell.imageChat.layer.masksToBounds = YES;
cell.imageChat.layer.borderWidth = 0;
if (cell.imageChat.image==nil) {
cell.imageChat.image=[UIImage imageNamed:@"profile.png"];

text=[cell.messageChat.text length];
return cell;

I'm trying this but not working:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
CGFloat height;
return height;

Please help me, i'm dying to do this @_@ Thanks in advance

Answer Source

Try this:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    // Fetch yourText for this row from your data source..
    NSString *yourText = [yourArray objectAtIndex:indexPath.row];

    CGSize labelWidth = CGSizeMake(300, CGFLOAT_MAX); // 300 is fixed width of label. You can change this value
    CGRect textRect = [visitorsPerRegion boundingRectWithSize:labelWidth options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[UIFont fontWithName:@"CenturyGothic" size:16.0]} context:nil];

    /* Here, you will have to use this requiredSize 
       and based on that, adjust height of your cell.
       I have added 10 on total required height of
       label and it will have 5 pixels of padding 
       on top and bottom. You can change this too. */

    int calculatedHeight = textRect.size.height+10;
    return (float)calculatedHeight;