Saturday, April 14, 2012

UITableView Overview

The most important component in a mobile is table, your music player contains a list of songs which you touch they begin to play well the component which holds all those songs is your table. In this blog i will demonstrate you on how to display names in the table from an array. Here's a glimpse of our final output



Step 1: Open Xcode and create a window based application and add a class file, only this time it wont be  a view controller class it would be a Tableviewcontroller subclass.



Now save this Tablecontroller subclass file with an appropriate name.

Step 2: Go to the .h file of your tableview controller class, i have named my file as myviewcontroller, declare an object of NSArray class which will hold the names of the countries which we want to display in our Table, here's the code for that

@interface myviewcontroller : UITableViewController {
NSArray *table_content;
}
@end

Step 3: Now go to the .m file of myviewcontroller and add objects to the array called table_content in the init method

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
table_content = [[NSArray alloc]initWithObjects:@"India",@"Germany",@"USA",@"South Africa",@"China",@"Japan",nil];
    }
    return self;
}

Step 4: since you have took a tableviewcontroller subclass then in this case you will be provided by the datasource and delegate methods by the tableviewcontroller subclass in your source code file here's how those method looks like



Let me give you an small explanation on those datasource protocol methods of the tableviewcontroller class

a) numberOfSectionsInTableView: Specifies the total number of section in a table view.

b)tableView numberOfRowsInSection: how many rows would be present in a table.

c)tableView cellForRowAtIndexPath: set the text for table.

d)tableView didSelectRowAtIndexPath: performs some action when the user selects any row of the table. 

These are the important functions which will be provided by the tableviewcontroller subclass by default in your source code file. (In my next blog i will show you how to display a sections which have some more methods of tableview datasource)

Step 5: now we will set the row and text of our table with the help of the functions tableView numberOfRowsInSection and tableView cellForRowAtIndexPath. I will explain the code one by one

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [table_content count];
}

The above function tells how many rows will my table have, i have used the count method of the array as i want the rows of the table as per my array count.

Now the next function is tableView cellForRowAtIndexPath and the only one line of code that you have to write in it is 

cell.textLabel.text = [table_content objectAtIndex:indexPath.row];

Step 6: Now go to the app delegate .m file and add the view to the window like this

#import "SimpleTableAppDelegate.h"
#import "myviewcontroller.h"
@implementation SimpleTableAppDelegate
@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after application launch
myviewcontroller *obj = [[myviewcontroller alloc]initWithStyle:UITableViewStyleGrouped];
[window addSubview:obj.view];
        [window makeKeyAndVisible];
}

Step 7: Build and run the application you will see the following output

Final output


Display Selected Text: Lets say you want to display the selected text of the Table into an alert view then in that case you can use the tableView didSelectRowAtIndexPath function. Here's the code to do that


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *str = [NSString stringWithFormat:@"%@",[table_content objectAtIndex:indexPath.row]]; //typecasting
UIAlertView *alertbox = [[UIAlertView alloc]initWithTitle:@"Table Demo" message:str delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK",nil];
[alertbox show];
}


Now when you run the application and select any of the rows of the table you will get the output just like the below images




Display Chevron: If you want to add some buttons with style then you can add chevrons in your table row, just go to the cellForRowAtIndexPath function and add this piece of code

[cell setAccessoryTypeUITableViewCellAccessoryDisclosureIndicator];

run the application you will see the following output

Table view with Chevrons


In the above image you can see the small arrows this arrows are called chevrons.

Delete a Particular Row: For this you have to use NSMutableArray and a UINavigationController class , here's how you will do that alloc and init the Mutable array just like we did the NSArray above and just add this piece of line in the init method

self.navigationItem.rightBarButtonItem = self.editButtonItem;

It means that you want to add an edit bar button item in the Navigation bar that will appear above the table.

Now uncomment the tableView commitEditingStyle method and just add this simple line, rest part is taken by the function itself, this function is used for inserting or deleting a row from the table.

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
[table_content removeObjectAtIndex:indexPath.row]; //delete elements from Mutable array...
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    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
    }   
}

Now just hop to the Appdelegate.m file and just make a few modifications

myviewcontroller *obj = [[myviewcontroller alloc]initWithStyle:UITableViewStyleGrouped];
UINavigationController *NAV = [[UINavigationController alloc]initWithRootViewController:obj];
[window addSubview:NAV.view];

The only new line to look at is the second line since we are going to add an edit button on the top of the table we will be requiring an NavigationController which is provided to us by NavigationController class.

The initWithRootViewController method asks us which view will be the main view and it takes the object of viewController class and finally adding the view to the window since NAV has all the data about the view, we will add NAV to the window

Finally build and Go you will get the following views

First view when you press Build and Go


The View when you press edit

The view when you select the round buttons

Final view when you press the delete button





DetailText Label: The table view cell has a property named detailTextLabel which can display some extra text on the table cell. So inorder to display that you have to change the style of the tableviewCell in the tableViewcellForRowAtIndexPath method

The line

   cell = [[[UITableViewCell allocinitWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier] autorelease];

Has a default style set so now you have to change the style, to subtitle and you will be done, UITableViewCellStyle is an enum so just change that line from the above to the code given below

  cell = [[[UITableViewCell allocinitWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:CellIdentifier] autorelease];


Of course there are some different styles present as well you may also try them, here’s a view at our final output.




Adding images to the table cell: You can also add images to the tableviewCell, and that too you have to do it in the tableViewcellForRowAtIndexPath method

Make sure that you have images in the resource folder

Here’s a look at my code and final output

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell allocinitWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
cell.textLabel.text = [mobile_name objectAtIndex:indexPath.row];
cell.detailTextLabel.text = @"Mobile name";
switch (indexPath.row+1) {
case 1:
cell.imageView.image = [UIImage imageNamed:@"apple.png"];
break;
case 2:
cell.imageView.image = [UIImage imageNamed:@"samsung.png"];
break;

case 3:
cell.imageView.image = [UIImage imageNamed:@"nokia.png"];
break;

case 4:
cell.imageView.image = [UIImage imageNamed:@"android.png"];
break;
case 5:
cell.imageView.image = [UIImage imageNamed:@"windows.png"];
break;
    return cell;
}

Table cell with images



I feel the code is self explanatory, I have used a switch case in order to determine the row and then added the image for the appropriate cell. 



i hope this post has helped you, Happy iCoding.

No comments:

Post a Comment