首页 > 解决方案 > UITableView加载错误的单元格高度Swift

问题描述

我正在使用 Xcode 10。我在 ViewController 中有一个表格视图。

单元格的标签设置为前导、拖曳、顶部和底部,行为 0

在 ViewDidload() 我添加

override func viewDidLoad() {
        super.viewDidLoad()
tableview.rowheight = UITableView.automaticDimension
tableview.estimateheight = 98
tableview.reloaddata()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentCell
        let  idcmt: String
        idcmt = self.CommentIDArray[indexPath.row]
        ref.child("Post_theme/\(userid!)/\(id)/comment/\(idcmt)").observe( .value, with: {(snapshot) in
            let value = snapshot.value as? NSDictionary

            cell.Comment.text = value!["content"] as? String
})

// I have a button in the custom cell but tableview load height wrong even I did not click the button on cell 

self.ref.child("Post_theme/\(self.userid!)/\(self.id)/comment/\(idcmt)/likecomment").observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.hasChild(self.userid!){
 cell.Heartcommentaction = {
                    cell.HeartCommentbutton.tintColor = .lightGray
                    self.TableCommentView.reloadData()
                }
}
})
return cell
}


class CommentCell: UITableViewCell{
var Heartcommentaction : (() -> ()) = {}
@IBOutlet weak var Comment: UILabel!
@IBOutlet weak var HeartCommentbutton: UIButton!
@IBAction func HeartCommentaction(_ sender: Any) {
        Heartcommentaction()
    }
}

但是当我点击 Viewcontroller 时,tableview 没有加载正确的高度单元格(需要自动调整的单元格不是,不需要的单元格是调整大小)

然后我添加这段代码

override func viewDidAppear(_ animated: Bool) {
       tableview.reloadData()
  }

该代码仅在最初的几个单元格中运行良好,但是当我向下滚动更多时(我有大约 100 多个单元格),它的高度再次错误,当我向上滚动初始单元格时再次出错

我看了很多解决方案,但不适合我

真的需要帮助!谢谢你

更新

这是错误高度单元格的屏幕截图,有时错误,有时正确

在此处输入图像描述

标签: iosswiftuitableview

解决方案


利用 :

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

同时删除tableview.estimateheight = 98


推荐阅读