UITableView cell background color - iphone

how to set different background colors for cells in a UITableView
(specifically rainbow color for seven cells)

Set the backgroundColor property:
cell.backgroundColor = [UIColor redColor];
Note that the backgroundColor must be set in the tableView:willDisplayCell:forRowAtIndexPath: method (from UITableViewCell reference):
Note: If you want to change the
background color of a cell (by setting
the background color of a cell via the
backgroundColor property declared by
UIView) you must do it in the
tableView:willDisplayCell:forRowAtIndexPath:
method of the delegate and not in
tableView:cellForRowAtIndexPath: of
the data source. Changes to the
background colors of cells in a
group-style table view has an effect
in iOS 3.0 that is different than
previous versions of the operating
system. It now affects the area inside
the rounded rectangle instead of the
area outside of it.
Use the indexPath parameter to achieve the rainbow effect.

If you want to set cell color based on some state in the actual cell data object, then this is another approach:
If you add this method to your table view delegate:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = cell.contentView.backgroundColor;
}
Then in your cellForRowAtIndexPath method you can do:
if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {
cell.contentView.backgroundColor = [UIColor blueColor];
}
This saves having to retrieve your data objects again in the willDisplayCell method.

Do not forget to set background color of your tableView to clearColor. Otherwise the clearColor of cell will not be displayed as the background color of tableView will be whiteColor by default. And even when the cell color turns to clearColor whiteColor will be displayed because the tableView background color is still whiteColor. Remenber.

You can set it like so:
cell.contentView.backgroundColor = [UIColor colorWithRed:249.0/255 green:237.0/255 blue:224.0/255 alpha:1.0];

Pretty sure UITableViewCell is a subclass of UIView, so:
cell.backgroundColor = [UIColor blueColor];
For awful rainbow colors, here is an example:
static NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor yellowColor], etc..., nil];
cell.backgroundColor = [colors objectAtIndex:indexPath.row];

Try this
cell.backgroundVIew.backgroundColor = [UIColor orangeColor];

If you've subclassed UITableViewCell, you can reliably set self.backgroundColor in -layoutSubviews. At least in my experience, this works in the odd cases where tableView:willDisplayCell:forRowAtIndexPath: does not.

You may arrive at the conclusion that 'willDisplayCell' is still not working like I did at first. The reason it didn't work for me initially was because I wasn't using colors properly.
Don't forget that when using custom colors you need to divide by 255.0f:
[UIColor colorWithRed:44/255.0f green:50/255.0f blue:65/255.0f alpha:1];
Something like the following will result to a white cell:
//DON'T DO
[UIColor colorWithRed:44 green:50 blue:65 alpha:1];
making it look like it's not doing anything when it really is setting the background to white.

Related

UILabel shadow from custom cell selected color

I'm loading a custom nib file to customize the cells of a UITableView. The custom nib has a UILabel that is referenced from the main view by tag. I would like to know if it is possible to change the shadow color of the UILabel when the cell is selected to a different color so it doesn't look like in the screenshot.
I prefer to make the shadow color change inside the TableCell code to not pollute the delegate. You can override this method to handle it:
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animate
{
UIColor * newShadow = highlighted ? [UIColor clearColor] : [UIColor whiteColor];
nameLabel.shadowColor = newShadow;
[super setHighlighted:highlighted animated:animate];
}
You could change the label's shadow color in -tableView:willSelectRowAtIndexPath: in the delegate. For instance:
-(NSIndexPath*)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.shadowColor = [UIColor greenColor];
return indexPath;
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.textLabel.shadowColor = [UIColor redColor];
}
I had the same issue and none of the above solutions quite worked for me - I didn't want to subclass UITableViewCell and also had some tricky selected/highlighted state changes done programmatically, which did not play well with the solutions above.
MySolution:
What I did in the end is to use a second UILabel underneath the primary UILabel to act as a shadow. For that 'shadow' UILabel you can set the 'Highlighted Color' to 'Clear Color'.
Obviously you have to update the shadow label each time you update the primary label. Not a big price to pay in many cases.
Hope that helps!
The simple answer, at least for the example shown above, is to not display the shadow in the first place. Since you can't see the white-on-white anyway, set the shadowColor to -clearColor.
If you actually need a shadow though, overriding the -setHighlighted method is the best solution. It keeps the code with the cell, which I think is better than trying to handle it from the table view.

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

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 in the cell.backgroundColor property only effects the contentView and not the accessoryView.
I have tried everything to set them to the same value. I tried to set the cell.backgroundView.backgroundColor and the cell.accessoryView.backgroundColor properties to the color I want but nothing is working. I also tried creating a subview inside contentView, which solved the backgroundColor problem (by avoiding it), but it creates the problem, where the switch sits on top of the cell.textLabel when the text is too long.
Is there are way I can modify the background color of the accessoryView without creating a subview in contentView, or to alter the length of the cell.textLabel without subclassing UITableViewCell?
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!
- (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...

UITableViewCell color issues with custom table view background

I have a UITableView with a custom background image set like this:
self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"mybg.png"]];
The background appears fine, but my UITableViewCells (default cells, not custom) have some sort of weird tint to them, and the UILabel containing the "New Project" text also seems to have some sort of background behind it. How can I remove this? I've already tried:
cell.backgroundColor = [UIColor clearColor];
cell.textLabel.backgroundColor = [UIColor clearColor];
Thanks
alt text http://cl.ly/Cg5/content
I believe that this is a nasty side-effect of simply adding an image straight into your table view's backgroundColor.
Try adding the image to the view's background color:
[[self view] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"mybg.png"]]];
and then set the table view's backgroundColor to be clear:
[[self tableView] setBackgroundColor:[UIColor clearColor]];
I hope this helps!
Some times when your working with setting images for an app, and testing on the simulator, they get frozen to the app for the few run. Not sure, this is the case even if you delete the image files; they still keep popping up.
I would make that you have rest the simulator, and restart Xcode. Then force a rebuild of the app back on the simulator. This should clear out any images- even background images if they are still being referenced.
If this is not a solution that works...try making sure that you don't have conflicting commands going to the same UiTablView object-(1 from IB and 1 from Xcode programmically). Sometimes you can overlook that you have set something in IB, and it conflicts with what your telling it to do programically.
If that doesn't solve the issue...check the connections in IB and make sure your reffrencing the correct IBOutlet UITableView *tableview. And you have the delegat and data protocols in the header.
If you want to have each cell set with background and want to remove text's background, maybe you can try this...
- (void)viewDidLoad {
...
self.tableView.backgroundColor = [UIColor clearColor];
...
}
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
...
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"mybg.png"]];
cell.textLabel.backgroundColor = [UIColor clearColor];
...
}

How do I fill the background color of a UITableViewCell?

How do I fill the background color of a UITableViewCell? I tried this code but it didn't work.
cell.backgroundColor = [UIColor redColor];
Try setting a backgroundView for UITableViewCell :
UIView *bgView = [[UIView alloc] init];
bgView.backgroundColor = [UIColor redColor];
cell.backgroundView = bgView;
// release object
[bgView release];
You can change the selection background view of UITableViewCell the same way.
cell.selectedBackgroundView = bgView;
Setting the background color though UITableViewCell's backgroundColor property only works in a Grouped table view. So if your table view is in the Plain style then it won't work.
You can of course set the background color of the UITableView's contentView. But then you probably have to do some additional work as the other subview (text labels and accessory views) have their own idea of background colors.
Take a look at the following snippet from the UITableViewCell documentation.
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html
Note: If you want to change the background color of a cell (by setting the background color of a cell via the backgroundColor property declared by UIView) you must do it in the tableView:willDisplayCell:forRowAtIndexPath: method of the delegate and not in tableView:cellForRowAtIndexPath: of the data source. Changes to the background colors of cells in a group-style table view has an effect in iOS 3.0 that is different than previous versions of the operating system. It now affects the area inside the rounded rectangle instead of the area outside of it.
That should solve your problem.

How can I set the background color of a cell in UITableView on iphone?

How can I set the background color of a cell in UITableView?
Thanks.
I know this is an old post, but I am sure some people are still looking for help. You can use this to set the background color of an individiual cell, which works at first:
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
[cell setBackgroundColor:[UIColor lightGrayColor]];
However, once you start scrolling, the iphone will reuse cells, which jumbles different background colors (if you are trying to alternate them). You need to invoke the tableView:willDisplayCell:forRowAtIndexPath. This way, the background color gets set before the reuse identfier is loaded. You can do it like this:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = ([indexPath row]%2)?[UIColor lightGrayColor]:[UIColor whiteColor];
}
The last line is just a condensed if/else statement. Good luck!
Update
Apparently the existing UITableViewCell framework makes it very difficult to change the background color of a cell and have it work well through all its state changes (editing mode, etc.).
A solution has been posted at this SO question, and it's being billed on several forums as "the only solution approved by Apple engineers." It involves subclassing UITableViewCell and adding a custom view for the subclassed cell's backgroundView property.
Original post - this solution doesn't work fully, but may still be useful in some situations
If you already have the UITableViewCell object, just alter its contentView's backgroundColor property.
If you need to create UITableViewCells with a custom background color, the process is a bit longer. First, you'll want to create a data source for your UITableView - this can be any object that implements the UITableViewDataSource protocol.
In that object, you need to implement the tableView:cellForRowAtIndexPath: method, which returns a UITableViewCell when given an NSIndexPath for the location of the cell within the table. When you create that cell, you'll want to change the backgroundColor property of its contentView.
Don't forget to set the dataSource property of the UITableView to your data source object.
For more info, you can read these API docs:
UITableViewDataSource - tableView:cellForRowAtIndexPath
UITableViewCell - contentView
UIView - backgroundColor
UITableView - dataSource
Note that registration as an Apple developer is required for all three of these links.
The backgroundView is all the way on the bottom. It's the one that shows the rounded corners and the edges. What you want is the contentView which is on top of the backgroundView. It covers the usually white area of the cell.
The version I wrote will work in iPhone 3.0 or higher and fallback to a white background otherwise.
In your viewDidLoad method of the UITableViewController we add the following:
self.view.backgroundColor=[UIColor clearColor];
// Also consider adding this line below:
//self.tableView.separatorColor=[UIColor clearColor];
When you are creating your cells (in my code this is my tableView:cellForRowAtIndexPath:) add the following code:
cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:#"code_bg.png"]];
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 3.0)
{
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
}
This works perfectly for me:
NSEnumerator *enumerator = [cell.subviews objectEnumerator];
id anObject;
while (anObject = [enumerator nextObject]) {
if( [anObject isKindOfClass: [ UIView class] ] )
((UIView*)anObject).backgroundColor = [UIColor lightGrayColor];
}
You may set the backgroundColor of the backgroundView. If the backgroundView does not exists, you can create one for it.
if (!tableView.backgroundView) {
tableView.backgroundView = [[UIView alloc] initWithFrame:tableView.bounds];
}
tableView.backgroundView.backgroundColor = [UIColor theMostFancyColorInTheUniverse];
If you want to set the background of a cell to an image then use this code:
// Assign our own background image for the cell
UIImage *background = [UIImage imageNamed:#"image.png"];
UIImageView *cellBackgroundView = [[UIImageView alloc] initWithImage:background];
cellBackgroundView.image = background;
cell.backgroundView = cellBackgroundView;