开发者

How do I create rows with alternating colors for a UITableView on iPhone?

开发者 https://www.devze.com 2022-12-25 06:16 出处:网络
i would to have alternate 2 colors of rows, like the first black, the second white, the third black, etc, etc...

i would to have alternate 2 colors of rows, like the first black, the second white, the third black, etc, etc...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
cell = ((MainCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]);
if (cell==nil) {

    NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:@"MainCell"    owner:self options:nil];

    for (id currentObject in topLevelObjects){
        if ([currentObject isKindOfClass:[UITableViewCell class]]){
            if ((indexPath.row % 2)==0) {
                [cell.contentView setBackgroundColor:[UIColor purpleColor]];

            }else{
                [cell.contentView setBackgroundColor:[UIColor whiteColor]];

            }
            cell =  (MainCell *) currentObject;
            b开发者_开发百科reak;
        }
    }

}else {

    AsyncImageView* oldImage = (AsyncImageView*)
    [cell.contentView viewWithTag:999];
    [oldImage removeFromSuperview];
}return cell;

The problem is that when i do a rapid scroll, the background of cells become like the last 2 cell black, the first 2 cell white or something like this, but if i scroll slow works fine. I think the problem is the cache of reusableCell.

Any ideas?

TIA


Cells get recycled (that is what you are doing when you dequeue them and check if it is nil). So instead of setting the background color when you create the cell, set it sometime after. So:

if( !cell ) {
  // create the cell and stuff
}
if( [indexPath row] % 2)
  [cell setBackgroundColor:[UIColor whiteColor]];
else
  [cell setBackgroundColor:[UIColor purpleColor]];


What I believe is happening is that when you dequeue a reusable cell, you do not do so in a defined order. As it would happen, when you scroll slowly, cells become available one at a time, and dequeued to you, in order. When you scroll quickly, the order becomes undefined, as does the order in which they are dequeued. I believe this is why (in large part) apple designed the UITableView API to dequeue by identifier - so you could reuse different types of cells, such as those with different colors, easily. As such, I recommend modifying the code to have each cell color have its own identifier. (Furthermore, if possible have an outlet connecting this tableview datasource to the cell directly, or save it in an ivar after loading it once, and then copy it rather than cycling through high level objects)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号