iOS dynamical height of UITableViewCell and heightForRowAtIndexPath

前端 未结 3 506
太阳男子
太阳男子 2021-01-04 23:24

I\'m using Autolayout for my new UITableViewCells in a large project.

I\'ve one TableView where the height of each row is calculated automatically, there I don\'t us

相关标签:
3条回答
  • 2021-01-04 23:37

    If you are using iOS 8 and above, you do not need to calculate height dynamically. Auto layout will do all for you. But if you are using lower than IOS 8, you need to calculate cell height.

    For IOS 8:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return UITableViewAutomaticDimension;
    }
    

    And add below code in your controller:

    tableView.estimatedRowHeight = 400.0
    tableView.rowHeight = UITableViewAutomaticDimension
    

    Where estimatedRowHeight should be max height which can be for your cell.

    Thanks

    0 讨论(0)
  • 2021-01-04 23:40

    You can try this.

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
        {
         int topPadding = cell.yourLabel.frame.origin.x;
         int bottomPadding = cell.frame.size.heigth-(topPadding+cell.yourLabel.frame.size.height);
         NSString *text = [DescArr objectAtIndex:[indexPath row]];
         CGSize maximumSize = CGSizeMake(cell.yourLabel.frame.size.width, 9999);
         CGSize expectedSize = [text sizeWithFont:yourCell.yourLabel.font constrainedToSize:maximumSize lineBreakMode:yourCell.yourLabel.lineBreakMode];
    
         return topPadding+expectedSize.height+bottomPadding;
    }
    
    0 讨论(0)
  • 2021-01-04 23:46

    Calculate the height of the content dynamically using boundingRectWithSize. If you have a UILabel which is dynamic, you can use the following :

    - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
       /* Check Content Size and Set Height */
        CGRect answerFrame = [YOUR_LABEL.text boundingRectWithSize:CGSizeMake(240.f, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName:[UIFont fontWithName:@"" size:14.0f]} context:nil];
    
        CGSize requiredSize = answerFrame.size;
    
        return requiredSize.height;
    }
    
    0 讨论(0)
提交回复
热议问题