如何使自定义UITableViewCell具有动态高度?

时间:2018-06-10 05:41:52

标签: ios swift xcode uitableview

我的目标是制作一个这样的屏幕:

enter image description here

这是我用StackView和Labels实现的屏幕。 但现在,我想用UITableView做到这一点。我的问题是细胞需要是动态的。因为文本可能与其他文本不同。 所以我开始用你的xib文件创建一个UITableViewCell(背景灰色是要设计的)

enter image description here

Swift文件

public class Entity : EntityBase {
   protected override object Keys {
      get {
         return SomeKeyProperty;//suppose this is a long property
      }
   }
   protected override object EmptyKeys {
      get {
         return 0L;//here 0 value should also be a long value.
      }
   }
}

使用UITableView的ViewController

class CellCreateSaleVC: UITableViewCell {


    @IBOutlet weak var lblInfo: UILabel!
    @IBOutlet weak var imgClipboard: UIImageView!
    @IBOutlet weak var lblNomeCampo: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)


    }

}

但我的结果是这样的: enter image description here

1 个答案:

答案 0 :(得分:0)

对于动态高度TableViewCell,您需要使用self-sizing table view cells,您必须将表视图的rowHeight属性设置为UITableViewAutomaticDimension。您还必须为estimatedRowHeight属性分配值。

tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableViewAutomaticDimension

要定义单元格的高度,请将细胞视图的约束添加到底边。如果您的视图具有内在的内容高度,系统将使用这些值。如果没有,则必须将适当的高度约束添加到视图或内容视图本身。

enter image description here

注意:

  

此外,尝试使估计的行高精确到   可能。系统计算滚动条高度等项目   基于这些估计。估计越准确,越多   无缝的用户体验。

请参阅this出色的堆栈溢出答案,以便为动态单元格高度使用自动布局。和raywendelich.com tutorial关于自我调整tableview单元格。

相关问题