Search code examples
iosswiftuitableviewuiscrollviewreloaddata

UITableView.sizeToFit() causes only first cell to be rendered


I have a standard UITableView, defined like so

self.productTable = UITableView(frame: CGRect(x:0, y:0, width: productsView.bounds.width, height: productsView.bounds.height), style: UITableViewStyle.plain)

    self.productTable.delegate = self
    self.productTable.dataSource = self
    self.productTable.isScrollEnabled = false

    self.productTable.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

I have this inside a UIScrollView, therefore I disable scroll also. When I get passed some new data I do the following

self.productTable.reloadData()
self.productTable.sizeToFit()

When I execute this, my cellForRowAt indexPath function only gets called once, resulting in only one cell being rendered.

If I remove the sizeToFit call, all rows are output with no problems.

Why is this the behaviour? I thought that reloadData was synchronous?

Thanks


Solution

  • After you reload the data once try below code instead of 'sizeToFit',

        CGRect newFrame = self.yourTableView.frame;
        newFrame.size.height = self.yourTableView.contentSize.height;
        self.yourTableView.frame = newFrame;
    

    And you should perform this on main thread!