2011-02-15 24 views
16

我需要遍歷TableView中的所有單元格,並在按下按鈕時爲cell.imageView設置圖像。我試圖讓每個單元格通過如何查找UITableView中的單元格數量

[[self tableView] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]]; 

但我需要計數的單元格。

如何查找TableView中單元格的數量?

回答

15

所有細胞的總數(在部分)應無論是被

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 

然而,這種方法越來越計數返回,你可以在你自己的方法做它也。可能類似於return [myArrayofItems count];

+0

爲什麼不出示swift3的代碼呢? – user44776 2017-07-11 10:07:50

6

UITableView僅用於查看從數據源獲取數據的方式。 單元總數是屬於數據源的信息,您應該從中訪問它。 UITableView擁有足夠的細胞,以適應您可以訪問使用

- (NSArray *)visibleCells

一個骯髒的解決辦法是保持你創建的每一個UITableViewCell的一個單獨的數組屏幕。它的工作原理,如果你的電池數量少,那就不是那麼糟糕。

但是,這不是一個非常優雅的解決方案,我個人不會選擇這個,除非絕對沒有其他方法。沒有相應的數據源更改,最好不要修改表中的實際單元格。

41
int sections = [tableView numberOfSections]; 

int rows = 0; 

for(int i=0; i < sections; i++) 
{ 
    rows += [tableView numberOfRowsInSection:i]; 
} 

總行數=行數;

4

基於Biranchi的代碼,這是一個小片段,它可以檢索每個細胞。 希望這可以幫助你!

UITableView *tableview = self.tView; //set your tableview here 
int sectionCount = [tableview numberOfSections]; 
for(int sectionI=0; sectionI < sectionCount; sectionI++) { 
    int rowCount = [tableview numberOfRowsInSection:sectionI]; 
    NSLog(@"sectionCount:%i rowCount:%i", sectionCount, rowCount); 
    for (int rowsI=0; rowsI < rowCount; rowsI++) { 
     UITableViewCell *cell = (UITableViewCell *)[tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:rowsI inSection:sectionI]]; 
     NSLog(@"%@", cell); 
    } 
} 
+0

感謝這絕對是真的,但正如上面所討論的...... tableviewcells總是從數據源加載......說一個數組....然後它更容易找到這個數! – sujith1406 2011-09-16 18:48:00

0

夫特3當量例如

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

     if section == 0 { 
      return 1 
     }else if section == 1 {  
      return timesArray.count // This returns the cells equivalent to the number of items in the array. 
     } 
     return 0 
    } 
1

夫特3.1(如2017年7月13日的)

let sections: Int = tableView.numberOfSections 
var rows: Int = 0 

for i in 0..<sections { 
    rows += tableView.numberOfRows(inSection: i) 
} 
0

擴展爲UITableView用於獲得行的總數。寫在Swift 4

extension UITableView { 

    var rowsCount: Int { 
     let sections = self.numberOfSections 
     var rows = 0 

     for i in 0...sections - 1 { 
      rows += self.numberOfRows(inSection: i) 
     } 

     return rows 
    } 
}