简体   繁体   中英

How do I modify the background color of an empty UITableViewCell object based on it's position?

I'm trying to write code to modify the background color of a cell based on it's position in the table. While the following code 'works', it only effects cells that are passed to it. Empty cells don't get effected.

- (void)tableView: (UITableView*)tableView willDisplayCell: (UITableViewCell*)cell forRowAtIndexPath: (NSIndexPath*)indexPath
{
    if(!indexPath.row%2)
    {
        cell.backgroundColor = [UIColor colorWithRed: 0.0 green: 0.0 blue: 1.0 alpha: 1.0] ;
        NSLog(@"Blue");
    }
    else{
        cell.backgroundColor = [UIColor whiteColor];
        NSLog(@"white");
    }
    cell.textLabel.backgroundColor = [UIColor clearColor];
    cell.detailTextLabel.backgroundColor = [UIColor clearColor];
}

How can I effect the rest of the cells that are displayed, if empty, when there are few items in the list?

By 'empty' cells, I mean the placeholder cells that are displayed when your data source doesn't have enough data to fill the entire view given to the table view. For example, if you can fit 10 cells, but only have 5 worth of data, you only ever get handed 5 cells to work with -- the next 5 are empty and as far as I can tell, unaccessable.

I guess you want to change the background only of "empty" cells ... Then you can change the backgroundColor in the InterfaceBuilder of the UITableView. But it will affect all empty cells.

You can also change the separator type.

Also, have a look here : http://www.zenbrains.com/blog/en/2010/06/color-de-fondo-de-celdas-vacias/

EDIT :

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // 7 depends on how many cell is shown
    return ([source count] <= 7) ? 7 : [source count];
}

From : Show blank UITableViewCells in custom UITableView

它应该工作如果设置了单元格的contentView的backgroundColor属性,而不是单元格的backgroundColor:

cell.contentView.backgroundColor = [UIColor colorWithRed: 0.0 green: 0.0 blue: 1.0 alpha: 1.0] ;

Try to add the following line

[[cell contentView] setBackgroundColor:[UIColor colorWithRed:0 green:128/255.f blue:0 alpha:1]];

in method

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

with the same logic you used in willDisplayCell method

as suggested here: http://www.zenbrains.com/blog/en/2010/06/color-de-fondo-de-celdas-vacias/

*notice that we change the background color for [cell contentView]

You should implement

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

in your delegate and initialize cells as you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM