how to set table cell height dynamically depending on text label length?

前端 未结 4 1905
终归单人心
终归单人心 2020-12-29 09:01

I am trying to learn Obj-C and iOS programming, but am still very new. I decided to try and make a simple Reddit client application. I am trying to display the front page po

4条回答
  •  抹茶落季
    2020-12-29 09:33

    In your tableview heightForRowAtIndexPath delegate method:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath   *)indexPath
    {
    
    if (indexPath.row == 2) {
      Message *aMessage = [customTableViewArray objectAtIndex:indexPath.row];
    
      if ( [aMessage.msgBody length] <= 0 )
        aMessage.msgBody = @"     ";
        CGSize constraint = CGSizeMake(450, 40000.0f);
        CGSize size = [aMessage.msgBody sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeCharacterWrap];
        size.height = MAX(size.height,36);
    
        return 136+size.height;
    
    } else if(indexPath.row > 1) {
    
          Message *aMessage = [customTableViewArray objectAtIndex:indexPath.row];
    
          if ( [aMessage.msgBody length] <= 0 )
            aMessage.msgBody = @"     ";
            CGSize constraint = CGSizeMake(450, 40000.0f);
            CGSize size = [aMessage.msgBody sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] constrainedToSize:constraint lineBreakMode:UILineBreakModeCharacterWrap];
            size.height = MAX(size.height,36);
    
            return 100+size.height;
    
    } else {
          return 146;
       }
    
    }
    

    I apologize, I had only included part of the code. This is the whole thing. So basically if the message is empty it makes it one size. Then in the else if part of the statement, it gets the size of the message and bases the cell size on that message size.

提交回复
热议问题