Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set background color of tableView

I have tried all the way but could not succeed to set backgroundColor of TableView. setting tableView.backgroundColor and/or cell.backgroundColor to clearColor didn't work when the parent view controller was UIViewContoller.

My nib file structure is

FileOwner
View
UITableView

(Note: i set the TableView to groupedTable section)

First attempt, I created the UIView in the code viewDidLoad

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 300)] autorelease;
[view setBackgroundColor:UIColor blueColor]; // color it just to see if it is created at the right place
[self.tableView sendSubViewToBack:view];

It works but it hides the content of cell. I am able to see the content of header but not cell content. (But when i change the co-ordinate of view(0,150,160,300) then i am able to see the cell's content but then it loose the backgroundColor of tableview.

Second attempt, I created the imageView

View
ImageView
UITableView

and set the self.tableView.backgroundColor = [UIColor clearColor]; but did not work.

I googled but did not the peaceful answer.

like image 853
Praveen Avatar asked Jan 20 '26 01:01

Praveen


2 Answers

A UITableView with the grouped style uses a background view. To get rid of the background view and let the background color show, try either of the following:

tableView.backgroundView = nil;
tableView.backgroundView = [[[UIView alloc] init] autorelease];

After that, you should be able to set the background color normally:

tableView.backgroundColor = [UIColor redColor];

BTW, only a view can be the parent/superview of another view, and a view controller is not a view.

like image 74
drawnonward Avatar answered Jan 21 '26 18:01

drawnonward


This has always worked for me:

UITableView *tableView = [[UITableView alloc] initWithFrame:tableFrame style:UITableViewStylePlain];
tableView.backgroundColor = [UIColor redColor];
[parentView addSubview:tableView];

Make sure that the tableView is not nil, not hidden, has the correct frame, and that it has been added to the correct parent view.

like image 30
MrHen Avatar answered Jan 21 '26 18:01

MrHen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!