How to find the number of Cells in UITableView
I need to loop t开发者_如何转开发hrough all cells in a TableView and set an image for cell.imageView
when I press a button. I'm trying to get each cell by
[[self tableView] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
But I need the count of cells.
How to find the count of cells in TableView?
int sections = [tableView numberOfSections];
int rows = 0;
for(int i=0; i < sections; i++)
{
rows += [tableView numberOfRowsInSection:i];
}
Total Number of rows = rows;
the total count of all cells (in a section) should be whatever is being returned by
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
however this method is getting count, you can do it in your own methods also. Probably something like return [myArrayofItems count];
UITableView
is designed only as a way to view your data, taken from the data source.
The total number of cells is an information that belongs in the data source and you should access it from there.
UITableView
holds enough cells to fit the screen which you can access using
- (NSArray *)visibleCells
One dirty solution would be to maintain a separate array of every UITableViewCell
you create. It works, and if you have a low number of cells it's not that bad.
However, this is not a very elegant solution and personally I wouldn't choose this unless there is absolutely no other way. It's better that you do not modify the actual cells in the table without a corresponding change in the data source.
based on Biranchi's code, here's a little snippet that retrieves every through cell. Hope this can help you !
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);
}
}
Swift (As of October 2020)
let sections: Int = tableView.numberOfSections
var rows: Int = 0
for i in 0..<sections {
rows += tableView.numberOfRows(inSection: i)
}
Swift 3 equivalent example
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
}
Extension for UITableView
for getting total number of rows. Written in 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
}
}
精彩评论