iphone - UITableView 在设备旋转后更正滚动位置

标签 iphone ios uitableview scroll screen-rotation

我正在构建类似书籍阅读器的东西。当用户旋转手机时,我想增加字体大小。我正在使用 UITableView 来显示文本 block 。

问题是,增加字体大小会增加我的表格 View 中行的高度,如果我在纵向模式下阅读第 320 段,我在横向模式下会得到 280 或类似的东西。

我已经使用这段代码设置了一个旋转通知监听器:

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

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

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

我希望它能在 iOS 4+ 上运行。

最佳答案

Swift 3 版本的 Said Ali Samed 的回答(willRotateToInterfaceOrientationdidRotateFromInterfaceOrientation 已弃用):

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)
        })
}

关于iphone - UITableView 在设备旋转后更正滚动位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258591/

相关文章:

ios - 当在 viewDidLayoutSubviews 中设置新的表格 View 框架时,iOS 7 应用程序崩溃

ios - 快速 NSPredicate 比较字符串

iphone - 在 iOS Storyboard中使用自动调整大小时,如何保证 UITableView 的单元格不会偏大

ios - Swift 包含数组的扩展

iphone - 在 Label 或 TextView 上开始一个新行(段落)

ios - 在 Swift 中加载其他元素后,在 TableViewCell 中异步加载一个元素

ios - UiCollcetionViewCell 特定的 segue 连接 TableView 显示 TableView 内的特定内容

iphone - 将自定义字体加载到我的应用程序中(Titanium Studio iPhone)

iphone - 我可以创建一个继承自 UIViewController 的自定义子类的 UITableViewController 吗?

iphone - 使用重叠 View 时不获取触摸事件