How to Change Table Background Color 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 color of the table 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<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, retain) NSArray *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];
[[self table] setBackgroundColor:[UIColor yellowColor]];
self.colorNames = [[NSArray alloc]initWithObjects:@"iPhone", @"iPad",@"iPod", @"Mac", @"Mac mini", nil];
}
- (NSInteger)tableView:(UITableView *)tableViewnumberOfRowsInSection:(NSInteger)section {
return [self.colorNames count];
}
- (UITableViewCell *)tableView:(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
UIImage *cellImage = [UIImage imageNamed:@"apple.png"];
cell.imageView.image = cellImage;
NSString *colorString = [self.colorNames
objectAtIndex: [indexPath row]];
cell.textLabel.text = colorString;
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end

Step 7

Click on the run button to show the output.

Output in iPhone:

Output-in-iPhone.png


Similar Articles