ios 如何让 UITableView 行高自动调整到 UITableViewCell 的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5161782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:05:00  来源:igfitidea点击:

how to get a UITableView row height to auto-size to the size of the UITableViewCell?

iphoneiosuitableviewautosize

提问by Greg

How to get a UITableView row height to auto-size to the size of the UITableViewCell?

如何让 UITableView 行高自动调整到 UITableViewCell 的大小?

So assuming I'm creating the UITableViewCell in Interface Builder, and it height is more than the standard size, how can I get the UITableView row height to autosize to it? (i.e. as opposed to manually having to measure the height in interface builder and than programmatically setting it)

所以假设我在 Interface Builder 中创建 UITableViewCell,并且它的高度超过标准大小,我怎样才能让 UITableView 行高自动调整到它?(即,与必须在界面构建器中手动测量高度而不是以编程方式设置高度相反)

回答by Brian

http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/is a great tutorial for this.

http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/是一个很好的教程。

The main bit is

主要的一点是

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
  // Get the text so we can measure it
  NSString *text = [items objectAtIndex:[indexPath row]];
  // Get a CGSize for the width and, effectively, unlimited height
  CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
  // Get the size of the text given the CGSize we just made as a constraint
  CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
  // Get the height of our measurement, with a minimum of 44 (standard cell size)
  CGFloat height = MAX(size.height, 44.0f);
  // return the height, with a bit of extra padding in
  return height + (CELL_CONTENT_MARGIN * 2);
}

回答by Mark Adams

If all the cells are the same, set the rowHeightproperty on UITableViewto the size of your cell. If they're all different based on content, you're going to have to implement -tableView:heightForRowAtIndexPath:and calculate the height for each row based on your data source.

如果所有单元格都相同,请将rowHeight属性设置为UITableView单元格的大小。如果它们因内容而异,则您将必须-tableView:heightForRowAtIndexPath:根据您的数据源实现和计算每行的高度。

回答by Andrei Stanescu

In the xib with your tableview, you can add a cell object and link it to an IBOutlet in your source-code. You won't use it anywhere, you will just use this to get the height of the cell.

在带有 tableview 的 xib 中,您可以添加一个单元格对象并将其链接到源代码中的 IBOutlet。你不会在任何地方使用它,你只会使用它来获取单元格的高度。

Then, in tableView:heightForRowAtIndexPath:you can use that object to get the height. It's not 100% automatic, but at least this saves you the trouble to manually update your source code when you make changes in the cell view in IB.

然后,tableView:heightForRowAtIndexPath:您可以使用该对象来获取高度。这不是 100% 自动的,但至少这可以为您在 IB 中的单元格视图中进行更改时免去手动更新源代码的麻烦。


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return myDummyCellObject.bounds.size.height;
}

If all rows are of the same type (cell) you can programatically set the tableView.rowHeightproperty instead of implementing the delegate method above. Depends on your scenario.

如果所有行都是相同类型(单元格),您可以通过编程方式设置tableView.rowHeight属性,而不是实现上面的委托方法。取决于你的场景。

Oh, and make sure you don't forget to release myDummyCellObject in -dealloc.

哦,请确保您不要忘记在-dealloc.

回答by Jayce

self.tableView.estimatedRowHeight = 65.0; // Estimate the height you want
self.tableView.rowHeight = UITableViewAutomaticDimension; // auto change heights for multiple lines cells.

When implement UITableViewDataSource required method:

实现 UITableViewDataSource 所需的方法时:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = [self.todoArray objectAtIndex:indexPath.row];
    cell.textLabel.numberOfLines = 0; // allow multiple lines showing up

    return cell;
}

回答by Aron

As of iOS 8 you have the option to work with self-sizing cellsby specifying these options on your table view:

从 iOS 8 开始,您可以通过在 table view 上指定这些选项来选择使用 self-sizing cells

tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableView.automaticDimension

This will work as long as the system can calculate the rows based on existing constraints or content. Take care that if you set automaticDimension then heightForRowAtIndexPath will not be called!

只要系统可以根据现有约束或内容计算行,这就会起作用。请注意,如果您设置了 automaticDimension,则不会调用 heightForRowAtIndexPath!



Sometimes with more complex data some cells can be calculated automatically, but others need a specific height calculation logic. In this case you should onlyset the estimatedRowHeight and then implement cellForRowAtIndexPath with automatic logic for the cells that can work correctly:

有时对于更复杂的数据,一些单元格可以自动计算,但其他单元格需要特定的高度计算逻辑。在这种情况下,您应该设置estimatedRowHeight,然后使用可以正常工作的单元格的自动逻辑实现cellForRowAtIndexPath:

// Set the estimated row height in viewDidLoad, but *not* automatic dimension!
override func viewDidLoad() {
    // other viewDidLoad stuff...
    tableView.estimatedRowHeight = 85.0
    tableView.delegate = self
}

// Then implement heightForRowAtIndexPath delegate method
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if theAutomaticCalculationWorksForThisRow {
        return UITableView.automaticDimension
    } else {
        // Calculate row height based on custom logic...
        let rowHeight = 85.0
        return rowHeight
    }
}