UITable view in iPhone

Creating the project
Create a new XCode project by clicking on File -> New Project -> (Under iPhone OS) select “Navigation-Based Application”, give it a name and save the project. I have named my project “TableView”. The project template “Navigation-Based Application” will give you a navigation controller and a table view tied together, so you do not have to set it up manually.



Data Source
Since we want to display not one or two but a list of items in the table view, we need some kind of a data source to hold our data and something which we can pass it on to the table view so it can use it. This data source can come from anywhere XML Files, Databases, or an array. To learn how to use SQL Lite databases read my SQL Lite tutorial series here. To keep this tutorial simple, I will choose a NSMutableArray as the data source for the table view. You can fill this array from XML files or SQLLite database. The array will be populated with string objects and not custom objects to keep the tutorial less confusing.



The first thing to do is to build the data source, populate it with the items we need to display in the table view. Let’s build our data source in viewDidLoad method of the RootViewController which is called when the view is loaded. This is how the header file and viewDidLoad method in the implementation file looks like



Array “listOfItems” is declared in RootViewController.h file and is of type NSMutableArray, it is also released in the dealloc method as shown above.
In viewDidLoad method, we allocate memory and initialize the array and add 8 objects to it. The view of the navigation bar is set to “Countries”. Now somehow we need to tell the table view to display the items in the array.
Customize the number of rows in the table view
The first thing we have to do is, tell the table view how many rows it should expect and this is done in tableView:numberOfRowsInSection. This method returns an integer which is the number of rows that the table view will display. Since our array consists of 8 objects, we will pass the count message to the array. This is how the code looks like

Display data in a table cell.
Now that the table view knows how many rows to display, we need to display the actual text which goes in a table view cell. The table view is made of table rows and rows contains table cell. This is done in tableView:cellForRowAtIndexPath which is called n number of times, where n is the value returned in tableView:numberOfRowsInSection. The method provides indexPath which is of type NSIndexPath and using this we can find out the current row number the table view is going to display. This is how the code looks like

//
//  RootViewController.h
//  UITableViewDemo
//
//  Created by Amplify Mindware on 13/02/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface RootViewController : UITableViewController {
    NSMutableArray *listofItems;

}


@end





#import "RootViewController.h"

@implementation RootViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    listofItems=[[NSMutableArray alloc] init];
    [listofItems addObject:@"Apple"];
    [listofItems addObject:@"Banana"];
    [listofItems addObject:@"Sugarcane"];
    [listofItems addObject:@"PineApple"];
    [listofItems addObject:@"StrawBerry"];
    [listofItems addObject:@"Chiku"];
    [listofItems addObject:@"Guava"];
    [listofItems addObject:@"Grapes"];
    [listofItems addObject:@"Papaya"];
    [listofItems addObject:@"Custard Apple"];
    [listofItems addObject:@"Jack fruit"];
    self.navigationItem.title=@"Fruits Bazar";
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}

/*
 // Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
 */

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [listofItems 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] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
    NSString *cellValue = [listofItems objectAtIndex:indexPath.row];
    cell.text = cellValue;
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert)
    {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    /*
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
*/
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload
{
    [super viewDidUnload];

    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc
{
    [super dealloc];
}

@end





Comments

Popular Posts