如何查找UITableView中的单元格数量

问题描述:

我需要遍历TableView中的所有单元格,并在按下按钮时为cell.imageView设置图像。我试图让每个单元格通过如何查找UITableView中的单元格数量

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

但我需要计数的单元格。

如何查找TableView中单元格的数量?

所有细胞的总数(在部分)应无论是被

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

然而,这种方法越来越计数返回,你可以在你自己的方法做它也。可能类似于return [myArrayofItems count];

+0

为什么不出示swift3的代码呢? – user44776 2017-07-11 10:07:50

UITableView仅用于查看从数据源获取数据的方式。 单元总数是属于数据源的信息,您应该从中访问它。 UITableView拥有足够的细胞,以适应您可以访问使用

- (NSArray *)visibleCells

一个肮脏的解决办法是保持你创建的每一个UITableViewCell的一个单独的数组屏幕。它的工作原理,如果你的电池数量少,那就不是那么糟糕。

但是,这不是一个非常优雅的解决方案,我个人不会选择这个,除非绝对没有其他方法。没有相应的数据源更改,最好不要修改表中的实际单元格。

int sections = [tableView numberOfSections]; 

int rows = 0; 

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

总行数=行数;

基于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

夫特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 
    } 

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

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

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

扩展为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 
    } 
}