Joe Huang Joe Huang - 2 months ago 14
iOS Question

In Swift, how to see the same cells for a table view when an orientation happens?

I have a table view whose cells and cell contents are arranged by auto layout. I also change cell height when orientation happens by returning different values in this function:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if (UIApplication.sharedApplication().statusBarOrientation.isLandscape.boolValue == true) {
// cell heights in landscape
if (...) {
return 100
} else
return 80
}
// cell heights in portrait
if (...) {
return 220
} else if (... ) {
return 240
} else {
return 250
}
}


When an orientation happens, everything works fine except that the visible cells are not the same. For example, let's say I have 30 cells in total. When I scroll the table in Portrait mode and I see cells 8, 9, 10, 11. And when I rotate the device to Landscape mode, I see cells 20, 21, 22, 23, 24.

I actually hope to see 8, 9, 10, 11 right after I rotate to Landscape mode in this case, which is the friendly behavior considering UI design.

The root cause is because the height of the cells are changed when the orientation happens. Is there any way I can adjust the table view so that I can see the same cells when the device orientation changes?

Answer

You could always do something like this:

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    yourTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: false)
}

To get the current visible top cell NSIndexPath you can do this:

yourTableView.indexPathsForVisibleRows![0]

indexPathsForVisibleRows returns an array of the NSIndexPaths of the visible cells in the UITableView and the first one at index 0 is the top one.