Swift,自动调整自定义表视图单元格

Luk*_*rts 2 xcode uitableview tableviewcell swift swift3

在我的应用程序中,我有一个表格视图,每个单元格中都有图像,标签和文本视图.我希望能够根据文本视图中的内容量自动调整单元格大小.(文本视图是最低的文本.)

到目前为止,我已经添加了正确的约束; 文本视图的前导,尾随,顶部和底部,并禁用滚动和编辑.

在我的tableViewController.swift文件中,我编写了这段代码:

override func viewWillAppear(_ animated: Bool) { tableView.estimatedRowHeight = 100 tableView.rowHeight = UITableViewAutomaticDimension }

但是,这不起作用,因为当我向文本视图添加更多文本时,它只是切断了.

也许这与卡片看起来有关,我在每个单元格中都有一个UIView作为卡片.

老实说,我不知道自己做错了什么

下面的图片是我的应用程序的样子,如果有人可以提供帮助,那将非常感激

在此输入图像描述

小智 8

检查您的约束是否如此(基于您的图像):

imageView:设置为容器的Top和Leading,具有修复高度和宽度值.

label:您可以将其设置为图像的顶部和水平空间,也可以设置固定高度和宽度.

textView:导致图像,顶部空间标签,尾部和底部到容器.

并继续使用

tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
Run Code Online (Sandbox Code Playgroud)

在你的viewWillAppear()中


小智 5

确保内容模式设置Scale To Fill为和卡片UITextView 没有高度限制UITextViewUIView

尝试将估计高度添加到viewDidLoad

override func viewDidLoad() {
    tableView.estimatedRowHeight = 100
    tableView.rowHeight = UITableViewAutomaticDimension
}
Run Code Online (Sandbox Code Playgroud)

UIView也许由于上述原因,自动高度不起作用UITextView。尝试在 中调用sizeToFitlayoutIfNeeded方法:UIViewcellForRowAt

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Identifier", for: indexPath) as! CustomTableViewCell
    cell.vwCard.sizeToFit()
    cell.vwCard.layoutIfNeeded()
    return cell
}
Run Code Online (Sandbox Code Playgroud)

您还可以尝试sizeToFitlayoutIfNeeded以及UITextView

希望这有效......


Zac*_*ack 5

迅速更新4.2

使用:

UITableView.automaticDimension
Run Code Online (Sandbox Code Playgroud)

代替:

UITableViewAutomaticDimension
Run Code Online (Sandbox Code Playgroud)