Lucas Pereira
Lucas Pereira

Reputation: 569

Set UIImage as background of a UITableView from a UITableViewController programatically

I have a MyTableViewController that is a subclass of UITableViewController. I have no .xib for it. And I'd like to set a UIImage I have as the background of the tableView from MyTableViewController. I tried to add on my ViewDidLoad : self.tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background_img"]];

But id didn't work. The img covered looked like this:

enter image description here

by doing:

UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background_img"]];
bgImageView.frame = self.view.bounds;
[self.view addSubview:bgImageView];
[self.view sendSubviewToBack:bgImageView];

it looks like this:

enter image description here

How Could I get that working?

Upvotes: 0

Views: 1245

Answers (2)

Petar
Petar

Reputation: 2283

You can do it as follows:

Set the background image in the tableView in viewDidLoad:

UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:<image>]];
bgImageView.frame = <tableView>.frame;
[<tableView> setBackgroundView:bgImageView];

Then set the colour of the cells to clear in tableView:willDisplayCell:forRowAtIndexPath::

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor clearColor];
}

Upvotes: 2

Josh Hudnall
Josh Hudnall

Reputation: 1031

You need to make the table view background transparent:

self.tableView.backgroundColor = [UIColor clearColor];
self.tableView.opaque = NO;

Then set the background of the view:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background_img"]];

A better way to set the background image, though would be:

UIImageView *bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background_img"]];
bgImageView.frame = self.view.bounds;
[self.view addSubview:bgImageView];
[self.view sendSubviewToBack:bgImageView];

Upvotes: -1

Related Questions