I have a UITableView whose data source and delegate are switched between a couple of custom data source objects when the user touches a segmented control (think \"Top Paid\"
One obvious work around is to have two separate table views that get swapped out, and each data source is permanently attached to one of the table views. This just seemed like a bit of a waste of memory, but perhaps I'm over-thinking it.
I used Corey's approach. I save & restore the rects with the dictionary representation. Also, it may not be obvious but the rect to preserve & restore is the bounds of the UITableView:
// Save the current tableview bounds
CGRect contentRect = self.listTableView.bounds;
if (!!oldScope) [_contentRects setObject:(NSObject *)CGRectCreateDictionaryRepresentation(contentRect) forKey:oldScope];
// Restore if possible
CFDictionaryRef restoredFrameDict = (CFDictionaryRef)[_contentRects objectForKey:newScope];
if (!restoredFrameDict) restoredFrameDict = CGRectCreateDictionaryRepresentation(CGRectZero);
CGRectMakeWithDictionaryRepresentation(restoredFrameDict, &contentRect);
// Switch over to new datasource
self.listTableView.dataSource = [self dataSourceForScope:newScope];
[self.listTableView reloadData];
// Restore content offset for "newScope"; Also stops scrolling
[self.listTableView scrollRectToVisible:contentRect animated:NO];
Note the interchangeable use of CFDictionaryRef
and NSDictionary *
You can also do self.tableView.isScrollEnabled = true/false
when you get to a certain tableView.contentOffset.y
value
Just found this looking for a way to stop my UIScrollView - I needed to move some subviews around, but this wound't look right if the user had flicked the screen and it was still decelerating.
Anyway - scrollRectToVisible
didn't work for me (maybe because I'm not using a table view??) but this worked perfectly:
[mainScrollView setContentOffset:CGPointMake(mainScrollView.contentOffset.x, mainScrollView.contentOffset.y) animated:NO];
I can then do the subview stuff without worrying!