How to indicate the color of each row in a table view?

In my application, I use one table. Now I want to split the two lines into alternate colors. This means that my first line will be white, my second line will be gray, the third will be white again ... So please, whoever has the solution for this. Then please share it. Thanks in advance.

Akshay

+4
source share
2 answers

Here is a relatively simple implementation:

In tableViewController implement 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; } 
+10
source

Voted answer is not accurate. On iOS6, you need to specify the background color of the contentView instead:

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

Source: https://habr.com/ru/post/1340638/


All Articles