首页 > 解决方案 > 从 contentSize 给出 tableview 高度时未调用 cellForRowAt indexPath

问题描述

我不知道为什么cellForRowAt indexPath不打电话。我检查delegate, datasource了它是正确的。而且我还检查了静态高度,然后它会起作用,但是当我constant从 tableview 内容大小给出 tableView 高度时,我不会打电话。这是我的代码。

//MARK: View life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        tblItemList.rowHeight = 76
        tblItemList.estimatedRowHeight =  UITableView.automaticDimension
    }

    override func viewWillLayoutSubviews() {
        heightConstraintForTblItem.constant = tblItemList.contentSize.height
    }

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

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    { 
            let cell = tableView.dequeueReusableCell(withIdentifier: "CheckOutItemCell", for: indexPath) as! CheckOutItemCell
            if arrProductList.count > 0 {
                let data = arrProductList [indexPath.row]
                cell.lblItemName.text = data.product_name ?? ""
                cell.lblQuantity.text = "\(data.product_total_quantity ?? 0)"
                cell.lblTotalPrice.text = CURRENCY + "\(data.product_total_amount ?? 0.0)"
            }

            return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if tableView == tblItemList {
            return UITableView.automaticDimension
        }
    }

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

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
            viewWillLayoutSubviews()
    }
}

标签: iosswiftiphoneuitableviewcontentsize

解决方案


尝试这个

1)删除func tableView(_ tableView: UITableView, estimatedHeightForRowAt方法和func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

2)删除viewWillLayoutSubviews方法

3) 在ViewDidAppear

 override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.view.layoutIfNeeded()
        self.heightConstraintForTblItem.constant = self. tblItemList.contentSize.height
        self.view.layoutIfNeeded()

    }

3)在您的 API 调用之后或当您在 tableview 中加载数据时

            self.tblItemList.reloadData()
            self.view.layoutIfNeeded()
            self.heightConstraintForTblItem.constant = self. tblItemList.contentSize.height
            self.view.layoutIfNeeded()

确保给定正确的约束,确保正确连接 IBOutlet,仔细检查数据源委托


推荐阅读