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

时间:2011-03-01 23:41:02

标签: iphone ios uitableview autosize

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

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

5 个答案:

答案 0 :(得分:37)

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

答案 1 :(得分:32)

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

答案 2 :(得分:13)

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

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


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

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

哦,确保你不要忘记在-dealloc中发布myDummyCellObject。

答案 3 :(得分:0)

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: MaterialCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! MaterialCollectionViewCell
    let item = items()[indexPath.item]
    //print(cell.contentView.subviews)
    for view in cell.contentView.subviews{
        view.removeFromSuperview()
    }
    //print(cell.contentView.subviews)
    let colors = [UIColor.grayColor(), UIColor.darkGrayColor()]
    cell.backgroundColor = colors[indexPath.item % 2]

    let showTitle: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height))
    showTitle.text = item.title
    showTitle.textAlignment = .Center
    showTitle.font = UIFont(name: "HelveticaNeue", size: 25.0)
    showTitle.textColor = MaterialColor.white
    showTitle.center = cell.center
    showTitle.hidden = true
    //print(showTitle.text)
    cell.contentView.addSubview(showTitle)


    let imageView: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: cell.frame.width, height: cell.frame.height))
    imageView.kf_setImageWithURL(NSURL(string: item.banner)!,
                                 placeholderImage: nil,
                                 optionsInfo: nil,
                                 progressBlock: { (receivedSize, totalSize) -> () in
                                    //print("Download Progress: \(receivedSize)/\(totalSize)")
        },
                                 completionHandler: { (image, error, cacheType, imageURL) -> () in
                                    //print("Downloaded and set!")
                                    if (image != nil) {
                                        showTitle.removeFromSuperview()
                                    }
                                    else {
                                        showTitle.hidden = false
                                    }
        }
    )
    cell.contentView.addSubview(imageView)
    //print(cell.contentView.subviews)
    return cell
}

实现UITableViewDataSource时需要的方法:

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

答案 4 :(得分:0)

从iOS 8开始,您可以通过在表格视图中指定以下选项来选择work with self-sizing cells

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

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


有时,如果数据更复杂,则可以自动计算某些像元,而其他像元则需要特定的高度计算逻辑。在这种情况下,您应该设置估计值RowHeight,然后为可以正常工作的单元格使用自动逻辑实现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
    }
}
相关问题