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

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

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

如果所有单元格都相同,请将UITableView上的rowHeight属性设置为单元格的大小。 如果它们根据内容完全不同,您将不得不实现-tableView:heightForRowAtIndexPath:并根据您的数据源计算每行的高度。

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

主要是

 - (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); } 

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

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

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

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

哦,并确保你不要忘记在-dealloc中释放-dealloc

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

当实现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; }