Altering the background color of cell.accessoryView and cell.editingAccessoryView

前端 未结 5 794
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 13:45

Whenever I add an accessoryView to my UITableViewCell, it doesn\'t carry the background color across? I\'m setting a UISwitch as my accessoryView, and the color I have set i

相关标签:
5条回答
  • 2020-12-05 13:57

    @Zak, first of all thanks for bringing to my attention the details of the cell layout. Very helpful!
    I would just like to point out that the following code:

    self.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_background.png"]];
    

    worked for me. The result was a background image stretching over whole cell. AccessoryTypeView didn't cover it! Important part is to put this code into layoutSubviews method of your custom cell class and not into cellForRowAtIndexPath found in TableViewController class. In my case I defined a class CustomCell and inside of it I have defined labels, image views etc.

    NOTE:The following code wasn't working:

    cell.contentView.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"cell_background.png"]];
    

    when put inside tableView:(UITableView *)tableView cellForRowAtIndexPat method. It was giving me the background covering the cell but AccessoryTypeView was above it...

    0 讨论(0)
  • 2020-12-05 13:59

    If you want to blend the accessory view background color with the background color of the cell, in iOS8 and Swift this worked like a charm in the tableView(_, cellForRowAtIndexPath:) method:

    let color = cell.contentView.backgroundColor
    cell.backgroundColor = color
    
    0 讨论(0)
  • 2020-12-05 14:00
     UIView *myView = [[UIView alloc] initWithFrame:cell.frame];
     myView.backgroundColor = [UIColor colorWithRed:214.00/255.00 green:233.00/255.00 blue:247.00/255.00 alpha:1.0];
     cell.backgroundView = myView;
     [myView release];
    
    0 讨论(0)
  • 2020-12-05 14:15

    Upon reading the documentation (a novel idea), I found the article, "A Closer Look at Table-View Cells". It helped me understand the composition of the cells, and I found my answer...

    cells look like this...

    alt text

    Since the cell.accessoryView is a sister view to cell.contentView I had to ask the cell.contentView for its superview, and then I was able to change the background color for both views at once. Here's what the code looks like...

    // Cell Formatting
    cell.contentView.superview.backgroundColor = [UIColor greenColor];
    

    I know it's really simple, but I'm a newbie and it took me ages to slow down and read the doc. Hopefully, this helps some other folks out there!

    0 讨论(0)
  • 2020-12-05 14:16
    - (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        cell.backgroundColor = [UIColor yellowColor];
    }
    
    0 讨论(0)
提交回复
热议问题