我有一个表格 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/