如何为tableview中的每一行赋予颜色?

Aks*_*her 4 uitableview ios4

在我的应用程序中我使用一个表.现在我想用替代颜色分隔两行.这意味着我的第一行将具有白色,我的第二行将具有灰色,第三行将再次具有白色...所以请任何人有解决方案.然后请分享.谢谢.

阿克沙伊

小智 10

这是一个相对简单的实现:

在您的tableViewController实现中,cellForRow使用以下内容:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"DefaultCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // check if row is odd or even and set color accordingly
    if (indexPath.row % 2) {
        cell.backgroundColor = [UIColor whiteColor];
    }else {
        cell.backgroundColor = [UIColor lightGrayColor];
    }

    return cell;
}
Run Code Online (Sandbox Code Playgroud)