1

Tableview offset changed after reload data.

1 Dynamic row height using auto layout.

2 Using Navigationbar and tabbar in UIViewController.

3 Using 2 header in tableivew (My 1st and 2nd header is static all dynamic rows in first section.)

Please check Log

First time load tableview

previousContentHeight -> 291.0 -- previousContentOffset -> 0.0

afterReloadDataContentHeight -> 3788.5 -- afterReloadDataContentOffset -> 0.0

New data arrived from server and reload data

previousContentHeight -> 3788.5 -- previousContentOffset -> 3063.5

afterReloadDataContentHeight -> 1719.0 -- afterReloadDataContentOffset -> 580.5

Here is reload data function

func prepareReloadData() {
    let previousContentHeight = tblView.contentSize.height
    let previousContentOffset = tblView.contentOffset.y
    print("previousContentHeight -> \(previousContentHeight) -- previousContentOffset -> \(previousContentOffset)")
    tblView.reloadData()
    tblView.layoutIfNeeded()
    print("afterReloadDataContentHeight -> \(self.tblView.contentSize.height) -- afterReloadDataContentOffset -> \(self.tblView.contentOffset.y)")
}
Community
  • 1
  • 1
Vivek
  • 4,916
  • 35
  • 40
  • How come after new data, your content size is reducing? – kerry Jun 20 '19 at 07:50
  • @kerry Yes notice, But I don't know why content offset is change and also change content size, When I scroll up everything is fine, First time 10 cell is visible, after api call another 10 cell is visible (Total 20 cell after api call). – Vivek Jun 20 '19 at 08:37

1 Answers1

1

After lots of time spent and find a solution to this issue

@Igor answer is working fine in this case

Here you can check original answer @Igor

Swift-5

// declaration & initialization  
var cellHeights: [IndexPath : CGFloat] = [:]

UITableViewDelegate

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    cellHeights[indexPath] = cell.frame.size.height
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return cellHeights[indexPath] ?? UITableView.automaticDimension // Here you can set specific height like 70 or your cell height instead of automaticDimension, But My suggestion is set automaticDimension
}
Community
  • 1
  • 1
Vivek
  • 4,916
  • 35
  • 40