如何为iPhone上的UITableView创建交替颜色的行?

Mat*_*Mat 10 cocoa-touch objective-c cell uitableview ios

我会有另外两种颜色的行,如第一个黑色,第二个白色,第三个黑色等等......

- (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;
            break;
        }
    }

}else {

    AsyncImageView* oldImage = (AsyncImageView*)
    [cell.contentView viewWithTag:999];
    [oldImage removeFromSuperview];
}return cell;
Run Code Online (Sandbox Code Playgroud)

问题是,当我进行快速滚动时,细胞的背景变得像最后2个细胞黑色,前2个细胞白色或类似的东西,但如果我滚动慢工作正常.我认为问题是reusableCell的缓存.

有任何想法吗?

TIA

Jas*_*oco 25

细胞得到回收(当你将它们出列并检查它是否为零时,你正在做的事情).因此,在创建单元格时不要设置背景颜色,而是在之后的某个时间进行设置.所以:

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