UITableView高度问题

时间:2019-02-28 22:37:26

标签: ios swift uitableview autolayout uistackview

我有一个UIStackView,并向其中添加了UIButtonUITableView作为subviews。最初,由于表格视图不包含任何内容,因此其高度为零。

用户执行操作时,UItableView会接收到一些数据并重新加载。

numberOfRowsInSection中返回计数,但是由于UITableView的高度为零,因此无法调用cellForRowAt

我要在没有内容的情况下将UITableView的高度保持为零,在有内容的情况下将其高度保持为空。

由于UITableViewUIStackView的子视图,因此它也应该扩展

我该如何实现?

2 个答案:

答案 0 :(得分:0)

您可以在表格视图接收数据后对其进行调整。检查此链接: UITableView not shown inside UIStackView

答案 1 :(得分:0)

嘿,我所做的事情与此非常相似,希望对您有所帮助。

final class SignInVC: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableViewHeight: NSLayoutConstraint!

    // Whatever max height you are after
    private let maxTableViewHeight = 500
    // Whatever height you are after
    private let rowHeight = 90

    // Just using string array for example but use your own array here
    private var fields: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.delegate = self
        tableView.dataSource = self
        setTableViewHeight()
    }

    private func setTableViewHeight() {
        var newHeight = fields.count * rowHeight
        if newHeight > maxTableViewHeight {
            newHeight = maxTableViewHeight
        }
        tableViewHeight.constant = newHeight
    }

    @IBAction func addField(_ sender: Any) {
        fields.append("Test")
        setTableViewHeight()
        tableView.reloadData()
    }

}

extension SignInVC: UITableViewDelegate, UITableViewDataSource {

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

    // Rest of your datasource/delegate below...
    // I am assuming you have your own already

}

希望这会有所帮助:)