Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give color to each row in the tableview?

In my app i am using one table.Now i want to separate two rows by alternate colors.That means my first row will have white color,my second row will have gray color third will have again white color likewise...So please anyone have solution for it.Then please share it.Thanks in advance.

Akshay

like image 477
Akshay Aher Avatar asked Dec 21 '22 17:12

Akshay Aher


1 Answers

Here is a relatively simple implementation:

In your tableViewController implement the cellForRow with something like this:

- (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;
}
like image 150
Chris Avatar answered Dec 24 '22 05:12

Chris