2012-03-02 31 views
8

獲取UITableView中最頂部部分的標題或索引的最準確方法是什麼?我不是指索引0處的部分,而是滾動時當前固定在頂部的部分標題。獲取UITableView的當前固定部分

回答

13

你可以在屏幕頂部的部分,像這樣:

 NSUInteger sectionNumber = [[tableView indexPathForCell:[[tableView visibleCells] objectAtIndex:0]] section]; 

但是,這種方法可能不是最適合你,因爲它會得到多少會奇怪,當它處於過渡期在兩個頭之間。只要你不需要知道過渡期間的部分,你應該沒問題。 我希望這是你想要的,

+0

我應該把什麼方法這保持sectionNumber電流是多少? – Bot 2012-03-02 20:37:39

+0

如果您希望每當用戶滾動時更新Scrollviewdidscroll – 2012-03-02 22:43:34

+1

輝煌,謝謝! – devios1 2013-07-23 22:57:23

-1

讓你的類實現UIScrollViewDelegate,並實現以下功能。 它將確保您僅在tableview停止滾動時檢索節。

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate 
{ 
    if (!decelerate) 
{ 
     // retrieve section here 
     section = [[[self.tableview visibleCells] objectAtIndex:0] section]; 
    } 
} 

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView 
{ 
     // retrieve section here 
     section = [[[self.tableview visibleCells] objectAtIndex:0] section]; 
} 
+0

我想這樣做,它可以防止部分在轉換時感到困惑的問題? – Bot 2012-03-02 20:31:42

+0

由於某種原因,我的自定義單元格拋出錯誤...' - [AppointmentCustomCell section]:發送到實例0x89af850'的無法識別的選擇器。我正在做的是NSLogging在你提供的上述代碼中的部分。 – Bot 2012-03-02 20:41:20

+0

這是舊的,但各種錯誤,因爲'self.tableView visibleCells'給出'UITableViewCells'而不是'IndexPaths'。獲得indexPaths後,我們可以做indexPaths [0] .section。 – esh 2017-06-08 18:01:05

3

我相信,而不是查詢的visibleCells,這是更好地索要指數路徑的方式如下:

NSInteger section = [[[self.tableView indexPathsForVisibleRows] firstObject] section]; 

您可以的UIScrollViewDelegate方法之一,根據使用該代碼的需要。

1

斯威夫特版本

使用第一(電流固定)或最後(最後顯示)

if let section:Int = tableView.indexPathsForVisibleRows?.last?.section { 

     tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: section), atScrollPosition: UITableViewScrollPosition.None, animated: true) 

    } 
相關問題