简体   繁体   English

更改静态UITableViewCell的高度以适合内容

[英]Change height of static UITableViewCell to fit content

Pretty much as the title says. 就像标题所说的一样。 I am looking at how to change the height of static UITableViewCell to fit content. 我正在研究如何更改静态UITableViewCell的高度以适合内容。 So I have several static sections with 1 TableViewCell within each. 所以我有几个静态节,每个节中都有1个TableViewCell。 The UILabels within are overflowing the UITableviewCell and I need it to fit. 里面的UILabel溢出了UITableviewCell,我需要它来适应。

在此处输入图片说明

What I'm struggling with: 我正在努力的是:

  • How to target static table cell (Is it the same as if dynamic? Use a reuse identifier? ) 如何定位静态表格单元格(与动态表格单元格一样吗?使用重用标识符?)
  • How to resize the static table cell dynamically to fit the content? 如何动态调整静态表格单元的大小以适合内容?

You have to implement the 您必须实施

tableView:heightForRowAtIndexPath: 

method of the UITableViewDelegate . UITableViewDelegate方法。 It's the only way to programmatically calculate the height of the cell and return it to the table when the table needs to display it. 这是以编程方式计算单元格高度并将其返回到表格(当表格需要显示时)的唯一方法。

Example

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = @"Your string";

    CGRect boundingBox = [string boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.view.bounds), CGFLOAT_MAX)
                                              options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
                                           attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14.0f]}
                                              context:nil];

    return CGRectGetHeight(boundingBox);
}

This solution is the cleanest and it works. 该解决方案是最干净的,并且有效。 The method above is part of the delegate protocol, which it seems can still be used to tweak the style and layout defined by the storyboard. 上面的方法是委托协议的一部分,似乎可以用来调整情节提要定义的样式和布局。 However, Apple does not recommend it: 但是,Apple不推荐这样做:

If a table view in a storyboard is static, the custom subclass of UITableViewController that contains the table view should not implement the data source protocol. 如果情节提要中的表视图是静态的,则包含表视图的UITableViewController的自定义子类不应实现数据源协议。 - Table View Programming Guide for iOS - 适用于iOS的Table View编程指南

So if you want to dynamically change attributes of the cell, use dynamic cells, not static. 因此,如果要动态更改单元格的属性,请使用动态单元格,而不是静态单元格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM