ios - 在 Swift 中,当方向发生时如何查看 TableView 的相同单元格?

标签 ios swift uitableview

我有一个表格 View ,其单元格和单元格内容是通过自动布局排列的。当方向发生时,我还通过在此函数中返回不同的值来更改单元格高度:

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if (UIApplication.sharedApplication().statusBarOrientation.isLandscape.boolValue == true) { 
        // cell heights in landscape
        if (...) {
            return 100
        } else
            return 80  
    }
    // cell heights in portrait
    if (...) {
        return 220
    } else if (... ) {
        return 240
    } else {
        return 250 
    }
}

当方向发生时,除了可见单元格不同之外,一切正常。例如,假设我总共有 30 个单元格。当我在纵向模式下滚动表格时,我会看到单元格 8、9、10、11。当我将设备旋转到横向模式时,我会看到单元格 20、21、22、23、24。

在这种情况下,我实际上希望在旋转到横向模式后立即看到 8、9、10、11,这是考虑到 UI 设计的友好行为。

根本原因是因为方向发生时单元格的高度发生了变化。有什么方法可以调整表格 View ,以便在设备方向改变时可以看到相同的单元格?

最佳答案

你总是可以做这样的事情:

override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
    yourTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: false)
}

要获取当前可见的顶部单元格 NSIndexPath,您可以执行以下操作:

yourTableView.indexPathsForVisibleRows![0]

indexPathsForVisibleRows 返回 UITableView 中可见单元格的 NSIndexPaths 数组,索引 0 处的第一个是顶部的。

关于ios - 在 Swift 中,当方向发生时如何查看 TableView 的相同单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34552999/

相关文章:

ios - swift 函数的默认返回类型是什么?

ios - 拒绝访问 : UserXXX is missing the Overall/Read permission

ios - 从 Unix 时间戳日期 ios 数组在 Uitableview 中创建动态部分?

ios - Swift:UITableViewCell 行高

ios - 如何防止sortedArrayUsingSelector删除重复条目(ios)?

ios - 为什么我的顶部和底部物理主体没有针对 iPad 调整大小?

ios - XIB 需要初始化器——没有 Storyboard

ios - 在后台模式下定期向服务器发送小数据

swift -3 : closure with escaping and non-escaping behaviour together

objective-c - 两个 UITableView 单元格/部分之间的黑色边框