UITableView with static cells without cellForRowAt

2020-02-16 12:02发布

问题:

I have a static UITableView and everything is laid out on the Storyboard. In cellForRowAtIndexPath i simply use

return [super tableView:tableView cellForRowAtIndexPath:indexPath];

and the tableview works great. However I want to set the cells backgrounds to [UIColor clearColor] How can I do this? The table has 30 cells, each one different.

Thanks

回答1:

I'm not entirely sure if this will work, because I've never tried using super to manage the cells. If your code works with super, then you should be able to get away with doing this to set the background color:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

Either way, this seems to me like a strange way of doing things. Normally the cells are created and reused in the method itself, as per the default UITableView boiletplate code, without calling super.



回答2:

Try this delegate method:

- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
 cell.backgroundColor = [UIColor clearColor];
}


回答3:

You can set up a method and call it in your viewDidLoad in order to get all the cells and do whatever you want with them you can use this:

NSArray *visibleIndexPaths = [self.tableView indexPathsForVisibleRows];

To get all the index paths of the currently viewable cells

Then iterate over them in the following way

UITableViewCell *cell = nil;
for (int i = 0; i < 30; i++) {
  cell = [self.tableView cellForRowAtIndexPath:[visibleIndexPaths objectAtIndex:i]];
  // Do your setup
}

You can also reference this Apple developer document the part "The Technique for Static Row Content"