Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 UITableView 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                                
           selector:@selector(orientationChanged:)
               name:UIDeviceOrientationDidChangeNotification
             object:device];

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+.

like image 704
Gio Avatar asked Sep 14 '25 05:09

Gio


1 Answers

Swift 3 version of Said Ali Samed's answer (willRotateToInterfaceOrientation and didRotateFromInterfaceOrientation are deprecated):

override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
    coordinator.animate(alongsideTransition: { context in
            // Save the visible row position
            self.visibleRows = self.tableView.indexPathsForVisibleRows!
            context.viewController(forKey: UITransitionContextViewControllerKey.from)
        }, completion: { context in
            // Scroll to the saved position prior to screen rotate
            self.tableView.scrollToRow(at: self.visibleRows[0], at: .top, animated: false)
        })
}
like image 173
Mohit Singh Avatar answered Sep 16 '25 19:09

Mohit Singh