UITableViewCell 动态高度以编程方式

UITableViewCell dynamic height programmatically

如何使用 UILabel 为 UITableViewController 中的 UITableViewCell 动态分配动态高度。

您可以使用委托方法

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

在上面的方法中,你可以 return 一个 CGFloat 变量,它具有针对 UITableView 的特定索引的单元格的动态高度

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

UIFont *font = [UIFont systemFontOfSize:20];
NSDictionary *userAttributes = @{NSFontAttributeName: font,
                                 NSForegroundColorAttributeName:     [UIColor blackColor]};
NSString *text = @"Your label text";

CGSize textSize = [text sizeWithAttributes: userAttributes];

ht = 20;

if (textSize.width > [FunctionUtils getViewWidth]) {

    ht = (textSize.width/([FunctionUtils getViewWidth]));
    ht = (ceil(ht))*20+35;
//20 font size
}

return ht;
}

对于动态 tableViewCell 高度,使用这个。

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  CGSize labelHeight = [self heigtForCellwithString:yourLabel.text    withFont:yourLabel.font];
    return labelHeight.height; // the return height + your other view height
}

-(CGSize)heigtForCellwithString:(NSString *)stringValue withFont:(UIFont)font{
 CGSize constraint = CGSizeMake(300,9999); // Replace 300 with your label width
  NSDictionary *attributes = @{NSFontAttributeName: font};
  CGRect rect = [stringValue boundingRectWithSize:constraint
                                       options:         (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                    attributes:attributes
                                       context:nil];
    return rect.size;

}