Thursday, April 7, 2011

How to maintain the UITableView scrolled location.

Recently, in one of my code, I discovered an issue in my UITableView's scrolled location. The issue was that, my UITableView was not maintaining its scroll location. My UITableView happens to be in a UIPopoverController and it has so many rows that it won't fit on screen. So it would take around 5 or 6 scrolls to see the entire contents of the UITableView.

So here is the exact problem:
On the main page, I have a name value. It is a superset of these name values that need to be displayed in the  UITableView when I click on a button to display the UITableView as a popover. What I need to do when the popover is displayed, is I need the name displayed on the main page to be shown as selected in the UITableView. Now if the name to be selected is within the first 20 rows in the UITableView then I have no issue, whenever the user clicks on the popover button, the tableview is shown with the required name selected.

However, if the name on my main page is a value that is not within the first 20 rows (maybe it is visible only after the 3rd or 4th scroll), so when I display the UITableView the selected value will not be seen because it is not in the current page. From a user point of view, this is a defect so I needed to correct it to improve the user experience.

This is how I fixed it.
 1. Calculate the saved scroll position. You can do it either by taking the content offset as follows:

CGPoint savedScrollPosition = [tableviewObject contentOffset];

or if this is not possible in some places, you can calculate the offset manually as follows:

int index = [namesArray indexOfObject:category.categoryName];
self.savedScrollPosition = CGPointMake(0, HEIGHT_OF_CELL * index);

2. Set the savedScrollPosition into the UITableViewController class.

3. In the viewDidAppear function of the UITableViewController class, write the following line:

[categories setContentOffset:savedScrollPosition animated:NO];

or you can set animation to yes if you want the animation.

So, eventhough I make a new instance of my UITableViewController each time the popover button is clicked, my users never lose their continuity.

Good trick!


  1. What is categories, in your application? I have the same problem as you describe, but don't know how to implement it since I don't know what 'categories' refers to in your case. I just have the UITableView class (called through a popover).

    1. Sorry for the late reply. Categories is the UITableView member variable. It is this UITableView that is shown as a popover. Hope this helps. Let me know if you need more help.

  2. how to get position of scroll side bar in UItableView at time of scrolling ??

    1. Hi veibav. I have already mentioned, just use the contentOffset property, its updated everytime the tableview is scrolled. Hope you got it.