设备旋转后UITableView校正滚动位置

Gio*_*Gio 2 iphone scroll uitableview screen-rotation ios

我正在为一本书建立类似读者的东西.当用户旋转手机时,我想增加字体大小.我用a UITableView来显示文本块.

问题是,增加字体大小会增加表视图中行的高度,如果我在纵向模式下读取段落320,我在横向模式下会得到280或类似的东西.

我已使用以下代码设置了旋转通知侦听器:

    UIDevice *device = [UIDevice currentDevice];                
    [device beginGeneratingDeviceOrientationNotifications];
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self                                
           selector:@selector(orientationChanged:)
               name:UIDeviceOrientationDidChangeNotification
             object:device];
Run Code Online (Sandbox Code Playgroud)

并尝试在旋转之前保存最后一个段落索引,然后在旋转后向下滚动到它,但我似乎无法达到预期的效果.

什么是处理这种情况的最佳方法,我在哪里实际实现"之前"和"之后"轮换状态?

我希望它可以在iOS 4+上运行.

Moh*_*ngh 5

Swift 3版本的Said Ali Samed的回答(willRotateToInterfaceOrientation并且didRotateFromInterfaceOrientation已被弃用):

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)
        })
}
Run Code Online (Sandbox Code Playgroud)