0

I have a UIStackView to which I add a UIButton and UITableView as subviews. Initially since the table view has no content it's height is zero.

When user takes an action the UItableView receives some data and reloads itself.

in numberOfRowsInSection I return the count but since the height of UITableView is zero call to cellForRowAt is not working.

I want to keep the height of UITableView zero when no content and give it height when the content is there.

And since UITableView is a subview of UIStackView it should expand too

How can I achieve it?

Avinash Sharma
  • 665
  • 1
  • 7
  • 23

2 Answers2

0

You could adjust tableview's frame once it receives data. Check this link: UITableView not shown inside UIStackView

JohnnL
  • 111
  • 11
0

Hey there I have done something very similar to this and hopefully this helps.

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

}

Hopefully this helps :)

Alex Dunlop
  • 1,383
  • 15
  • 24