Tuesday, February 06, 2007

Alternate TableView Row Colors in iPhone

When displaying tableView with many rows, alternating the background color of each row can increase readability. If you don't know number of rows for tableview you cant do this from interface builder. This can be easily done from tableview method willDisplayCell. Add the following code to your implementation file which contains delegate and datasource methods for your tableview.

-(void) tableView:(UITableView *) tableView
willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row % 2 ){
NSLog(@"inside alternate cells");
cell.backgroundColor =
[UIColor colorWithRed:147.0/255.0 green:160.0/255.0 blue:169.0/255.0 alpha:1.0];
}
}

your tableview will look like below:




of course i have customized cell according to my requirement.

Read my Objective C presentation at: Objective C for iPhone Development