Hi all,
In today’s tutorial we will study how we can customize a UITableView using “Prototype Cells” in iOS which was introduced
in XCode 5.0.
First Create a new Project and Name it “CustomTBLView”.
Now you will get the Main.storyBoard file with other ViewController and Delegate Files.
Open Main.storyBoard and “Drag” a TableView on to it.
Now Drag a “UITableViewCell” on to it. This is the Prototype Cell.
Now our “Main.storyBoard” looks like this.
Now select the tableView cell from the Hierarchy and Go to the “Attributes Inspector” on the right side.
Select Style = ” Basic ”
Indentifier = “list_item_cell”
Now you will see that a “Label” will appear in the cell.
Click on the label and go to “Attributes Inspector” and give tag as “100”.
Here “list_item_cell” is the identifier for each prototype cell.
We will use this identifier to get the cell and populate the items.
[ Make sure you like the “delegate” and “datasource” to the ViewController, otherwise no data will be loaded in
the tableview ]
Our work in the Interface Builder is over.
Now Lets do the coding part
Go to the ViewController.h and paste the delegates and the array
ViewController.h
#import <UIKit/UIKit.h> @interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { } @property (strong, nonatomic) NSMutableArray *_tblData; @end
Now go to ViewController.m and synthesize the array.
These are the delegate methods
- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView { } - (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section { } - (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath { }
Now your ViewController.m will look like this.
#import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize _tblData; - (void)viewDidLoad { [super viewDidLoad]; if (!_tblData) { _tblData = [[NSMutableArray alloc] initWithObjects:@"iPhone", @"Android", @"Windows", @"Apple", @"Google", @"Microsoft", nil]; } } - (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView { return 1; } - (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section { return [_tblData count]; } - (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list_item_cell"]; UILabel *lblName = (UILabel *)[cell viewWithTag:100]; [lblName setText:[_tblData objectAtIndex:[indexPath row]]]; return cell; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end
OK Done. Run the project.