ios - UITableViewCell 的动态高度无法正常工作

标签 ios swift uitableview dynamic swift4

我的动态 UITableViewCell 有一些高度问题(缝下图)。有些单元格的高度正确,有些则没有,当我拖动 tableView 时,有些单元格变得正确,有些则不正确。

我正在使用此代码使单元格的高度变为动态并在 viewDidAppear 中重新加载它和 viewDidLoad .

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = tableView.rowHeight

如前所述,单元格有时是正确的,有时不是。还有其他方法可以做到还是我做错了什么?我尝试了许多不同的解决方案,都提到了here以及 StackOverflow 和其他网站上的其他建议。

enter image description here

enter image description here

我感谢所有帮助!

编辑!

TableView
extension ChatVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return groupMessages.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "groupFeedCell", for: indexPath) as? GroupFeedCell else { return UITableViewCell() }

        let message = groupMessages[indexPath.row]

            DataService.instance.getUsername(forUID: message.senderId, handler: { (name) in
                cell.configureCell(name: name, content: message.content)
            })

        cell.layoutSubviews()
        cell.layoutIfNeeded()

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return UITableViewAutomaticDimension
    }

    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
}

细胞
@IBOutlet weak var nameLbl: UILabel!
@IBOutlet weak var contentLbl: UILabel!

func configureCell(name: String, content: String) {
    self.nameLbl.text = name //email
    self.contentLbl.text = content
}

enter image description here

最佳答案

对于动态tableViewCell

1-使用行高的初始值设置这 2 行,以帮助自动布局绘制它(从 nib 文件中的当前单元格高度获取)

tableView.rowHeight = UITableViewAutomaticDimension;
tableView.estimatedRowHeight = number;

2-不要实现这个功能 heightForRowAtIndexPath .或实现它并返回这个
return UITableViewDynamicHeight;

3-确保单元 Nib 文件或 Storyboard 中的所有约束从上到下正确连接。

4- in cellForRowAtIndexPath 在行重新运行单元格之前插入
[cell layoutSubviews];
[cell layoutIfneeded];

5- 在模拟器中测试一些版本,如 ios 8,这也是 viewController 调用中的一个错误
[tableView LayouSubviews];

在 viewdidLayoutSubViews 函数中重新正确重新布局

6-制作任何 的属性(property)UIL标签 你想要包装 = 0 并 Hook 它是 领先 尾随 superView 的约束

关于ios - UITableViewCell 的动态高度无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47716661/

相关文章:

ios - zxing 专注于 iOS

iphone - appDelegate 方法发生错误

swift - 如何快速访问单元格内的 UIStackView 实例?

function - Swift 中的内联条件表达式中调用函数

ios - 如果 Collection View 嵌入在 ios 中的 TableView 中,如何始终显示 Collection View 的第一项

ios - Viewcontroller 在被另一个 viewcontroller 呈现后崩溃

ios - swift : update of view constraints not visible

ios - 返回数组的函数没有在 for 循环 Swift 中获取附加内容

ios - 整个应用程序都使用相同的 UISearchBar?

ios - 在 Swift 中选择时关闭 UITableView Cell?