如何根据 table 行设置动态 table 高度?

How to set dynamic table height based on table row?

我在 运行 时面临 table 身高问题。

我在超级视图中添加了一个滚动视图。在滚动视图上,我在顶部添加了一个 UIView,然后在 UIView 之后我放置了一个 UITableView(scrollEnabled false),并再次在我的 UITableView 底部添加了一个 UIView。

问题:我希望用户在屏幕上滚动一次,所以我禁用了 table 视图滚动 属性。现在我的问题是我正在从服务器获取 table 数组数据,因此在从服务器获取数据后,我的 viewDidLayoutSubviews 方法没有在我编写 table 高度逻辑的地方被调用。当我重新加载相同的屏幕时,一切正常。

这是我的代码:

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        if devicesArray.count != 0{
            viewDeviceList.frame = CGRect(x: viewDeviceList.frame.origin.x, y: viewDeviceList.frame.origin.y, width: viewDeviceList.frame.size.width, height: tableDeviceList.contentSize.height)

            tableDeviceList.reloadData()
        }

    }

任何人都可以就此向我提出建议。谢谢。

请尝试使用以下代码并告诉我。我正在与观察者一起工作,它工作得很好。

//MARK:- Add this observer into your View/Controlloer
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            self.transactionTableViewHeightConstraints.constant = transactionTableView.contentSize.height
        }
//MARK:- Fetch TableListData
    func updateTableViewHeightAfterAPICall(){
            self.transactionTableView.addObserver(self, forKeyPath: "contentSize", options: [], context: nil)
            self.transactionTableView.reloadData()
            UIView.animate(withDuration: 0.5) {
                self.view.layoutIfNeeded()
            }
        }

像这样为 tableView 高度约束创建 outlet

@IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!

添加这一行

self.tableView.reloadData()
self.tableViewHeightConstraint.constant = self.tableView.contentSize.height