Dynamic custom UITableViewCell height based on label text length

I'm a noob in Xcode and Objective-C and I need help to create a dynamic view table cell height, about how many characters are in the label. So it will be: if textLabel char is more than 10, it will resize the listHeight to 50 else if textLabel char is more than 20, this 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 am trying this but not working:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   CGFloat height;
   if(text>=10){
      height=100;
   }
   else
      height=70;
   return height;
}

      

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

+3


source to share


2 answers


Try the following:

- (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;
}

      



👍 Hope it works !!!

+6


source


An alternative to @ Pratik's answer if you want to use dynamic text sizes would be something like a class method in a cell.

What do we do at work



+ (CGFloat)cellHeightForTitle:(NSString*)title inTableView:(UITableView*)tableView{
    UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
    NSString *text = title ?: @"test"; // Just some text
    CGFloat hotizontalPadding = 0; // account for other content for calculating width of the cell
    CGFloat desiredWidth = tableView.bounds.size.width - hotizontalPadding;
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];

    UILabel *label = [[UILabel alloc] init];

    label.attributedText = attributedText;
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    CGSize size = [label sizeThatFits:CGSizeMake(desiredWidth, CGFLOAT_MAX)];

    font = nil;
    attributedText = nil;

    return size.height;
}

      

+1


source







All Articles