How to Set Background Image on Table in iPhone

Introduction

In this article I will create a Single View application. Here I will add a table view using outlet and connect it's delegate and datasource to the file owner. To change the background image of a table view we write code for the viewdidload method.

To better understand it we use the following procedure.

Step 1

Open XCode by double-clicking on it.

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now Select Single View Application and click on "Next".

Step 4

Now provide your Product Name and Company Identifier. 

Step 5

Select the location where you want to save your project and click on "Create".

Step 6

Now we write the code of the Objective-C classes:

TableExampleViewController.h

//
// TableExampleViewController.h
// TableColor
//
// Created by Sachin Bhardwaj on 24/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import <UIKit/UIKit.h>
@interface TableExampleViewController : UIViewController<UITableViewDelegateUITableViewDataSource>
@property (nonatomicretainNSArray *colorNames;
@property(strong,nonatomic)IBOutlet UITableView *table;
@end

TableExampleViewController.m

//
// TableExampleViewController.m
// TableColor
//
// Created by Sachin Bhardwaj on 24/01/13.
// Copyright (c) 2013 Sachin Bhardwaj. All rights reserved.
//

#import "TableExampleViewController.h"
@interface TableExampleViewController ()
@end
@implementation TableExampleViewController
@synthesize colorNames,table;
- (void)viewDidLoad
{
[super viewDidLoad];
UIImage *img = [UIImage imageNamed:@"images.jpeg"];
[[self table] setBackgroundColor:[UIColor colorWithPatternImage
:img]];
self.colorNames = [[NSArray alloc]
initWithObjects:@"Red", @"Green",
@"Blue", @"Indigo", @"Violet", nil];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.colorNames count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [colorNames objectAtIndex:indexPath.row];
return cell;
}
@end

Step 7

Click on the run button to show the output.

Output in iPhone:

output-in-iPhone.png