2014-10-02 122 views
11

我將在其中使用2個部分進行tableview。我可以以編程方式添加細胞到每一個部分,當我加入,我用滾動的tableview結束iOS UITableView滾動到部分底部

[_tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)]; 

我的問題是如何可以滾動到段0的末尾,這樣當用戶添加單元格到0節,tableview動態滾動到0節的最後一個單元格。

謝謝。

回答

22

您可以使用此代碼嘗試:

int yourSection = 2; 
int lastRow = [tableView numberOfRowsInSection:yourSection] - 1; 
[tableView scrollToRowAtIndexPath:[NSIndexPath lastRow inSection:yourSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES]; 

你得到行數在你的部分,然後滾動至indexPath。

+0

謝謝,它像一個魅力 – 2014-10-02 12:27:40

+0

這是我給你一個索引超出該行號的界限。你需要減去1 – Moriya 2015-07-29 09:41:55

+1

請務必記得檢查該部分是否存在,並且有多於該行的數量,否則會崩潰。 – Benetz 2015-07-29 10:17:51

4

當你在結束插入行,你有它的索引路徑,你可以使用的tableview的scrollToIndexPath方法滾動

[self.liveChannelsTable scrollToRowAtIndexPath:IndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES]; 
+1

謝謝,它的工作還 – 2014-10-02 12:28:55

15

所有上述建議是正確的,至少基於該文檔。但它沒有在我的情況下工作 - 我無法讓滾動顯示錶視圖中的最後一行。我必須在滾動中添加延遲才能完成這項工作。

- (void)scrollToTheBottom:(BOOL)animated 
{ 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowCount-1 inSection:0]; 
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:animated]; 
} 

我叫上面:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
      [self scrollToTheBottom:YES]; 
}); 
+0

謝謝。我在我的一個部分中進行了大量計算,除了這一部分之外,沒有滾動解決方案可以工作。 – wheeliez 2015-05-28 12:05:10

+0

謝謝。此解決方案修復了滾動到最後一個單元格時最後一個單元格不可見的問題。 – 2015-06-17 14:44:37

+0

爲此,我嘗試了很多,但無法工作任何代碼,但你的代碼再次爲我工作。 – 2016-08-03 11:08:54

2

以防萬一,這是解決方案斯威夫特:

extension UITableView { 
    func scrollToBottom(animated: Bool = true) { 
     let sections = self.numberOfSections 
     let rows = self.numberOfRowsInSection(sections - 1) 
     self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true) 
    } 
} 
1

在斯威夫特3它已經更新爲:

let indexPath = IndexPath(row: self.numberOfRowsInSection(0) - 1), section: 0) 
self.commentsTableView.scrollToRow(at: indexPath, at: .bottom, animated: false)