2016-06-08 167 views
0

我有一个自定义表格视图单元格,我想根据标签中的文本量自动调整大小。自动调整大小自定义UITableViewCell

这是我的手机。我想调整它的大小以显示评论标签中的所有文字。 enter image description here

在我的表视图控制器我用UITableViewAutomaticDimension

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     if indexPath.section == 0 { 
      if indexPath.row == 0 { 
       return 200 
      } else { 
       return 49 
      } 
     } else if indexPath.section == 1 { 
      return 100 
     } else if indexPath.section == 2 { 
      if indexPath.row == 0 { 
       return 200 
      } else { 
       return 400 
      } 
     } else { 
      return UITableViewAutomaticDimension 
     } 
    } 

    override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
     return UITableViewAutomaticDimension 
    } 

这是我结束了。

enter image description here

+0

确保将contentView的尾部,前导,顶部和底部连接到其子视图。 – genaks

+0

你看过这篇文章吗? http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights – Dominic

+0

做一些像[链接](http:// useyourloaf。 com/blog/table-view-cells-with-varying-row-heights /),它会帮助你 –

回答

0

请确保您有在顶部,底部设置的限制,尾随并从孩子导致利润率的内容查看你有UIView或任何子元素。这可以帮助你

enter image description here

在你的情况,你需要定义从ReviewLabel底部间隔限制的内容查看,使其工作。相应的UILabel s也需要顶部,尾部和领先的利润空间。顶部空间可以从DateLabel定义,而前后空格可以从包含星号的UIView中定义。

为什么?

contentView需要知道它的子视图的框架才能使uitableviewautomaticdimension工作。如果它不知道它的子视图帧的话,那就不知道如何自动调整大小以

0

实现委托函数的高度算了一笔账:

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { 
    let cell = tableView.cellForRowAtIndexPath(indexPath) 
    let size = cell.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) 
    return size.height + 1.0 // Add 1.0 for the cell separator height 
} 
0

您需要:

  1. 为您的标签设置top, trailing, leading, bottom对IB中superView的约束
  2. numberOfLines = 0
  3. Content Compression Resistance Priority VerticalContent Hugging Priority Vertical
  4. 代码self.tableView.estimatedRowHeight = MinControlSize;self.tableView.rowHeight = UITableViewAutomaticDimension;

,并设置文本后调用此

cell.setNeedsDisplay(); 
cell.layoutIfNeeded(); 
在委托方法

optional func tableView(_ tableView: UITableView, 
heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat 

希望这有助于集。我从Apple的Self Sizing示例中获得了此示例