Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView set background color

Tags:

I change the background color of the UITableViewCells in the tableView:cellForRowAtIndexPath method

    if(indexPath.row % 2 == 0){         cell.backgroundColor = ...     } else{         cell.backgroundColor = ...     } 

But that only change the color of the cell amount specified in tableView:numberOfRowsInSection (As seen in the attached picture, there are white cells after the first four)

Is it possible to change the color of all cells that are displayed on screen?

enter image description here

like image 712
Sp0tlight Avatar asked Jul 14 '14 18:07

Sp0tlight


2 Answers

  1. Open Storyboard
  2. Select your UITableView
  3. Open Attribute inspector
  4. Scroll to View group
  5. Select background color for entire table.

enter image description here

like image 102
Keenle Avatar answered Sep 21 '22 15:09

Keenle


If you want the cell background color to continue to alternate, then you need to lie about how many rows are in the table. Specifically, in tableView:numberOfRowsInSection you need to always return a number that will fill the screen, and in tableView:cellForRowAtIndexPath, return a blank cell for rows that are beyond the end of the table. The following code demonstrates how to do this, assuming that self.dataArray is an NSArray of NSStrings.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {     if ( self.dataArray.count < 10 )         return( 10 );     else         return( self.dataArray.count ); }  - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SimpleCell"];      if ( indexPath.row % 2 == 0 )         cell.backgroundColor = [UIColor orangeColor];     else         cell.backgroundColor = [UIColor redColor];      if ( indexPath.row < self.dataArray.count )         cell.textLabel.text = self.dataArray[indexPath.row];     else         cell.textLabel.text = nil;      return cell; } 
like image 26
user3386109 Avatar answered Sep 18 '22 15:09

user3386109