views:

2811

answers:

3

Is there any way to set a background view on a UITableViewController?

I try with the code I am using on a UIViewController, but the view comes over all the contents of the table view, and if I add the background view in the cellForRowAtIndexPath-method, it is not showing at all. Anyone done this before or have an idea on how it can be done? Here is the code I am using:

UIImage *image = [UIImage imageNamed: @"background.jpg"];
UIImageView *backImage = [[UIImageView alloc] initWithImage: image];
[self.view addSubview: backImage];
[self.view sendSubviewToBack: backImage];

Thanks

+3  A: 

Actually, I got it working! :)

NSString *backgroundPath = [[NSBundle mainBundle] pathForResource:@"background" ofType:@"jpg"];
UIImage *backgroundImage = [UIImage imageWithContentsOfFile:backgroundPath];
UIColor *backgroundColor = [[UIColor alloc] initWithPatternImage:backgroundImage];
self.tableView.backgroundColor = backgroundColor; 
[backgroundColor release];
Hans Espen
A: 

Great solution. Tried a few things but nothing worked for me. This one is really great!

+4  A: 

(This is basically the same as Hans Espen's solution above, but uses convenience methods for brevity)

Put this in your -[UITableViewControllerSubclass viewDidLoad] method:

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

There's no point in avoiding a couple of autoreleases in a viewDidLoad method, since it only gets called rarely (when the view actually loads) and will therefore have negligible impact on performance.

N.B. You should always use PNG images on the iPhone, not JPEG or any other format.

Nick Forge
Why only .png for iOS ?
Pierre Valade
I should clarify - use PNG for everything that isn't photographic. PNGs are hardware accelerated by the GPUs on iOS devices, so all of your UI images should be in PNG format. PNG supports alpha transparency, which is a necessity for a lot of UI graphics. For anything photographic, JPEG compression will give you smaller file sizes, so that may be a benefit.
Nick Forge