简体   繁体   English

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

[英]How to set dynamic table height based on table row?

I am facing table height issue at run time.我在运行时面临桌子高度问题。

I have a Scroll View added to my Super view.我在超级视图中添加了一个滚动视图。 Over the Scroll View, I have added a UIView in the top then after UIView I have placed one UITableView (scrollEnabled false) and again have added a UIView in the bottom of my UITableView.在滚动视图上,我在顶部添加了一个 UIView,然后在 UIView 之后我放置了一个 UITableView (scrollEnabled false),并再次在我的 UITableView 底部添加了一个 UIView。

Problem: I want user to do a single scroll in the screen, so I have disabled table view scrolling property.问题:我希望用户在屏幕上滚动一次,所以我禁用了表格视图滚动属性。 Now my problem is I am fetching table array data from server so after getting data from server, my viewDidLayoutSubviews method is not getting called where I have wrote the table height logic.现在我的问题是我正在从服务器获取表格数组数据,所以在从服务器获取数据后,我的 viewDidLayoutSubviews 方法没有在我编写表格高度逻辑的地方被调用。 And when I am re-loading the same screen then everything is working fine.当我重新加载同一个屏幕时,一切正常。

Here is my code :这是我的代码:

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()
        }

    }

Can anyone suggest me on this.任何人都可以就此向我建议。 Thank you.谢谢你。

Please try with below code and let me know.请尝试使用以下代码并告诉我。 I'm working with observer and its working perfectly.我正在与观察者一起工作,它工作得很好。

//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()
            }
        }

Create outlet for tableView height constraint like this像这样为 tableView 高度约束创建出口

@IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!

add this line添加这一行

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM