![](/img/trans.png)
[英]How to access cells of a table view of a view from another view in Swift?
[英]In Swift, how to see the same cells for a table view when an orientation happens?
我有一個表格視圖,其單元格和單元格內容通過自動布局進行排列。 我還通過在此函數中返回不同的值來更改定向發生時的像元高度:
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設計的友好行為。
根本原因是因為定向發生時單元格的高度發生了變化。 有什么方法可以調整表格視圖,以便在設備方向更改時可以看到相同的單元格?
您總是可以這樣做:
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
yourTableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: false)
}
要獲取當前可見的頂部單元格NSIndexPath,可以執行以下操作:
yourTableView.indexPathsForVisibleRows![0]
indexPathsForVisibleRows
返回UITableView中可見單元格的NSIndexPaths數組,索引0處的第一個是頂部的數組。
override func willRotateToInterfaceOrientation (toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval
{
// Save the visible row position
visibleRows = tableview.indexPathsForVisibleRows;
}
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation)
{
// Scroll to the saved position prior to screen rotate
}
選中此按鈕可獲得一個想法。
對於iOS 10 / Xcode8 / Swift 3,將以下內容添加到UITableView:
// retain same position in UITableView on screen rotation
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
let indexPath = tableView.indexPathsForVisibleRows![0]
tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: false)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.