[英]Scroll table view to bottom when using dynamic cell height
使用動態單元格高度時,如何將表格視圖滾動到底部?
出於某種原因,此代碼在此方案中不起作用:
[self.tableView scrollRectToVisible:CGRectMake(0, self.tableView.contentSize.height - self.tableView.bounds.size.height, self.tableView.bounds.size.width, self.tableView.bounds.size.height) animated:YES];
謝謝!
編輯 :使用@ Hasiya的代碼滾動到底部,對於你們中的一些人來說可能就是這樣。
以下內容適用於我的Swift 3.1代碼,使用Xcode 8.3.2僅針對iPhone的iOS 10.1。
我和OP有同樣的問題。 我的應用程序包括消息功能。 當消息視圖被推入堆棧時,我希望最后一個帖子可見。 由於消息的內容,我的tableview單元格高度是可變的。 沒有一個解決方案令我滿意(最后一個tableview行不可見或只是部分可見)。 但是,這對我有用:
在viewController中,在'viewDidLoad'函數中實現tableview,設置tableview的'rowHeight'屬性,如下所示:
myTableView.rowHeight = UITableViewAutomaticDimension
同樣在'viewDidLoad'函數中,將tableview的'estimatedRowHeight'設置為高於您預期的平均行高的值。 在我的情況下140。
最后也是最重要的是我寫了這段代碼:
extension UITableView {
func scrollToBottom() {
let rows = self.numberOfRows(inSection: 0)
let indexPath = IndexPath(row: rows - 1, section: 0)
self.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
請注意at: .top
- 這就解決了我的問題。 傳遞UITableViewScrollPosition
參數的.bottom
值不起作用。 即使通過.middle
工作 - 但不是.bottom
。
因此,每當我的數據集需要更新或新消息到達時,我都會打電話
func getTableViewData(){
// Get your data here any way you usually do..
// call to reload
myTableView.reloadData()
// call the scroll function
myTableView.scrollToBottom()
}
我通過簡單地改變測試此“方法”的結果at: .bottom
參數at: .top
。 每當我將其更改at: .top
,最后一個表行完全可見,表格一直滾動到底部。
最終, 我找到了答案 。 滾動到底部的原因不起作用(插入/刪除行也是錯誤的,正如我后面發現的那樣)是因為not properly estimated
單元格高度。 要解決此問題,請嘗試在estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
返回近似估計estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
。 但是,如果你不能這樣做(並且在大多數情況下你將無法做到),仍然有一個很好的解決方案:將單元格的高度存儲在字典中,並在重復使用單元格時返回estimatedHeight
的高度(例如滾動表格視圖)。 我在另一個問題中找到了這個解決方案,所以請去查看實際代碼,了解如何實現這一目標。 (雖然可能,很多人都可以為自己寫這個)
編輯:也許修復只是滾動到底部這是不必要的,但在我看來強烈推薦。 如果您不使用它來估計行高,您將遇到其他問題,例如錯誤的滾動和大量單元格的性能下降。
您還需要將此添加到viewDidAppear
let lastItem = IndexPath(item: dataSource.count - 1, section: 0)
tableView.scrollToRow(at: lastItem, at: .bottom, animated: true)
希望這可能對你有用。 試試這個
[self.tableview setContentOffset:CGPointMake(0, CGFLOAT_MAX)]
要么
if (self.tableview.contentSize.height > self.tableview.frame.size.height)
{
CGPoint offset = CGPointMake(0, self.tableview.contentSize.height - self.tableview.frame.size.height);
[self.tableview setContentOffset:offset animated:YES];
}
嘗試使用scrollToRowAtIndexPath,如下面的代碼所示。
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSInteger no = array.count-1;
NSIndexPath *lastIndex = [NSIndexPath indexPathForRow:no inSection:0];
[self.tableView scrollToRowAtIndexPath:lastIndex atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
我通過這個簡單的步驟來實現它:
1)在IB中手動將估計高度設置為高於預期的值2)在viewWillAppear中滾動到最后一行,ScrollPosition參數為UITableViewScrollPositionTop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.