UiTableview doesn't update sizetofit in iOS 10 but working in iOS 11

816 views Asked by At

I am creating a dynamic TableView and i set the cell with the rowheight of 44 in the storyboard. So the tableview's height will be based on the number of rows that my database returns according to the results. At the same time, i am connecting the tableView's bottom constraint to the view with an IBOutlet. So the tableview's height will not overlay the keyboard and keep some distance with some configuration. My question is how can i update the tableView.frame.size.height with sizeToFits() in iOS 10 and lower?

Here are some logs to have clearer image, tableView and contentView size for iOS 10

Another image when the tableview's sizetofit() never increase from smaller to larger. Another logs , it will be gone completely if my database returns 0 result then for the contentSize will be 0.0 and then when i try to remove some texts, the contentSize will back to 44 because got 1 result from database and by right the SizeToFit() will fit the size based on the contentSize. But in this case, it still stick with 0.0 and never update.

Image for iOS 11, tableView and contentView size for iOS 11, the height for the tableview with 632 is correct because i did set some auto layout to prevent interfere with the keyboard so user can scroll down within the tableView.

Some codes for better understanding,

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // configuration for tableViewCell.

    tableView.sizeToFit() // WORKs for iOS 11 but doesn't update for iOS10 

    if UIDevice.current.userInterfaceIdiom == .pad {
        tableView.setNeedsLayout()
        tableView.layoutIfNeeded()
        cell.backgroundColor = UIColor.darkGray
    }

    return cell
}
1

There are 1 answers

0
usergio2 On

I am not sure what do you want to achieve. Assuming you want your tableView size to be the same with its content you should actually manipulate the constraint of your UITableView height.

You need to set the height after you update your tableView dataSource. If you are using sizeToFit() you should also do it after updating your tableView dataSource

// using sizeToFit
func loadData(){
    allData  = loadFromDatabase()
    tableView.reloadData()
    tableView.sizeToFit()
}

If you choose to manually calculate and set your constraint you can try

func resizeTableView(){
    allData  = loadFromDatabase()
    tableView.reloadData()
    let tableFrame = tableView.frame
    tableFrame.size.height = tableView.contentSize.height
    tableView.frame = tableFrame
}

I personally will set the frame manually or set the constraint instead of sizeToFit, due to some bugs reported when using sizeToFit