【问题标题】:How to change each UITableViewCell height dynamically?如何动态改变每个 UITableViewCell 的高度?
【发布时间】:2015-09-24 11:17:27
【问题描述】:

我正在开发在 UILable 中显示用户评论的应用程序,并且 UILable 具有 sizetofit 属性。我想根据 UILable 高度更改单元格高度。

我的问题是我如何更改单元格高度,例如第一个单元格高度可能是 50,第二个单元格高度可能是 100,依此类推。

【问题讨论】:

  • 你有单元格预期高度的列表吗?

标签: ios uitableview sizetofit


【解决方案1】:

对于 UITableViewCell 的动态高度,您必须执行以下操作

  • 满足 UITableViewCell 中的所有约束要求
  • 使用以下代码告诉您的 TableView 动态布局每个单元格的高度

    - (void)viewDidLoad {
         [super viewDidLoad];
    
         // two magic lines
         tableView.estimatedRowHeight = 89
         tableView.rowHeight = UITableView.automaticDimension
    }
    

只需两行代码,您就可以指示表格视图计算与其内容匹配的单元格大小并动态呈现它。这种自我调整大小的单元格功能应该可以为您节省大量的代码和时间。你会喜欢的。

【讨论】:

  • 您可以将它用于具有 tableView 的 viewController 中,这是一个有用的教程,一步一步解释>fantageek.com/1468/…
【解决方案2】:

在您的 heightForRowAtIndexPath 中,根据相关单元格数据计算动态高度。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
 { 
     NSDictionary *data = [self.dataSource objectAtIndex:indexPath.row];
     return [MyTableViewCell heightForData:data];
 }

然后在您的 MyTabLeViewCell 中,编写如下函数,假设数据具有“内容”,即动态高度的事实。并且您的 tableViewCell 定义了一个名为 contentLabel 的 UILabel 与 CONTENT_LABEL_WIDTH

+(CGFloat) heightForData : (NSDictionary *)data{

    self.contentLabel.text = [data objectForKey:@"content"];
    CGSize contentLabelSize = [self.contentLabel sizeThatFits:CGSizeMake(CONTENT_LABEL_WIDTH, CGFLOAT_MAX)];

    return contentLabelSize.height;

    //If you want to have a minimum cell height no matter how small your content is, you can use below fmaxf with a pre-defined CELL_MIN_HEIGHT value.
    // return fmaxf(CELL_MIN_HEIGHT, height);
}

【讨论】:

    【解决方案3】:

    您可以使用此方法动态增加UITableViewCell 高度(无自动布局)

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        NSMutableAttributedString *strName = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",strItemName]];
    
        [strName addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, strItemName.length)];
        CGSize sizeItemName = CGRectIntegral([strName boundingRectWithSize:CGSizeMake(130, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil]).size;
        int padding = 5;
        //your default cell height for ex 55 
        if (sizeItemName.height < 55)
        {
            sizeItemName.height = 55;
        }
        return sizeItemName.height + padding;
    }
    

    【讨论】:

      【解决方案4】:

      希望通过 tableview 方法对您有所帮助:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-27
        • 1970-01-01
        • 1970-01-01
        • 2014-05-19
        • 1970-01-01
        • 2019-10-12
        相关资源
        最近更新 更多