I subclassed UITableViewCell to set a cell background color to a color I need:
.h
@interface DataViewCustomCell : UITableViewCell {
UIColor* cellColor;
UIColor* standardColor;
}
- (void) setCellColor: (UIColor*)color;
@end
.m
@implementation DataViewCustomCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}
- (void) setCellColor: (UIColor*)color
{
cellColor = color;
}
- (void) spreadBackgroundColor: (UIView*)that withColor: (UIColor*)bkColor
{
NSEnumerator *enumerator = [that.subviews objectEnumerator];
id anObject;
while (anObject = [enumerator nextObject]) {
if([anObject isKindOfClass: [UIView class]])
{
((UIView*)anObject).backgroundColor = bkColor;
[self spreadBackgroundColor:anObject withColor:bkColor];
}
}
}
- (void) layoutSubviews {
[super layoutSubviews]; // layouts the cell as UITableViewCellStyleValue2 would normally look like
if(!self.selected && NULL != cellColor)
{
[self spreadBackgroundColor:self withColor:cellColor];
}
}
- (void)dealloc
{
[super dealloc];
}
@end
When I call setCellColor with the color I want, all goes well, but when I haven't found a way to set the original color back: when I set [UIColor clearColor]
with UITableViewStylePlain style the results is not good-looking.
How can I achieve a good result, without a missing cell separator line?
I was having a similar problem and found edo42's answer. However I was then having an issue with the background behind the text in the cell not displaying the background color I set. I believe this is due to the style: UITableViewCellStyleSubtitle.
In case others stumble upon this question, I believe the better solution for this is found in this question:
BackgroundColor of UITableViewCellStyleSubtitle labels? BackgroundColor of UITableViewCellStyleSubtitle labels?
Answer reprinted here:
To change the background color of the table view cell, you'll need to set it in tableView:willDisplayCell:forRowAtIndexPath: rather than tableView:cellForRowAtIndexPath: otherwise it won't have any effect, for example:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [UIColor whiteColor];
}
Finally, I solved it by myself. I used the following code in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
instead of subclassing:
UIView *bg = [[UIView alloc] initWithFrame:cell.frame];
bg.backgroundColor = [UIColor greenColor]; //The color you want
cell.backgroundView = bg;
cell.textLabel.backgroundColor = bg.backgroundColor;
[bg release];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With