Gio Gio - 1 year ago 106
iOS Question

UITableView correcting scroll position after device rotation

I'm building something like a reader for a book. When the user rotates the phone I want to increase the font size. I'm using a

to display chunks of text.

Problem is that, increasing the font size increases height of rows in my table view and if I was reading paragraph 320 in portrait mode I get 280 or something similar in landscape mode.

I have set up a rotation notification listener using this code:

UIDevice *device = [UIDevice currentDevice];
[device beginGeneratingDeviceOrientationNotifications];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self

and tried to save the last paragraph index before rotation and then scroll down to it after the rotation but I can't seem to achieve desired effect.

What's the best way to handle this kind of situation and where do I actually implement "before" and "after" states of rotation?

I'd like it to work on iOS 4+.

Gio Gio
Answer Source

Since I couldn't get a good answer I'll answer myself. I've looked everywhere but couldn't find a way to do what I wanted so I just used the shouldAutorotateToInterfaceOrientation method to increase the size of font and then start a little thread that sleeps for 0.2 seconds and after that scrolls to the desired row. Thanks for your help.

Edit: Use delegate method willRotateToInterfaceOrientation: to store the visible cell in an array then use the delegate method didRotateFromInterfaceOrientation: to scroll to the visible index path that you recorded in the array.

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
    // Save the visible row position
    visibleRows = [tableview indexPathsForVisibleRows];

    // Scroll to the saved position prior to screen rotate
    [tableView scrollToRowAtIndexPath:[visibleRows objectAtIndex:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];