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

余生颓废 提交于 2019-11-28 21:12:13

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...

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!

Aalok Bhatwal
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor yellowColor];
}
 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];

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

@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...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!