Wednesday, February 27, 2013

Table View in iPhone Tutorial


Today we are going to create very simple application to understand understand How Table View works in iOS.

While you are writing code for iOS Application.

I Always keeps in mind below written Five steps while developing iOS application.

1. Create All the Required Files 
2. Design UI (Using Interface Builder)
3. Write Objective -C code for functionality  (in .h and m files as well)
4. Need to hook-up or UI Items with Objective-C code (Using file owner).
5. Execute the application

So let's Fire!! Xcode .

PHASE - I

Create New Project this way

1. File --> New --> Project -->Empty Application.

2. In the Next Window Screen put the Values as 

Product Name: TableViewDemo
Org Name : RDCWorld
Company Identifier (package name) : com.rdcworld

Class Prefix : (leave blank for now)

Devices : select iPhone (if its not selected)

then check Tick mark for "Use Automatic Reference Counting" option to enable ARC.

and click on Finish button.

3 . After creating initial app, you can see the Default Xcode Dashboard with having Project Structure on Left side.

we have mainly these files so far.

AppDelegate.h
AppDelegate.m
main.m

So now we need to Add one UIViewController to show our table View.

so here we go ..

1. Right click on project (Blue Icon) 

New File -->iOS (Cocoa Touch) --> Objective -C class --> Next

In the next window screen you need to put values like this 

Class : MyViewController
Subclass of : UIViewController

Make a Tick Mark on "With XIB fo.r user interface" option.


then go Next.. --> Create.

Good!! now you can see Three more new files added to our project

MyViewController.h
MyViewController.m
MyViewController.xib

Okay we have created all the required files, So far our Project Structure is looking like below snap shot




PHASE - II

Now we need to handle design things if we have any.
In this application we just use UITableView only so its pretty simple.

Just open MyViewController.XIB file.
(You can see blank Layout with white background )

Now look at the UI Library (on Bottom Right Side in XCode)
and Drag the UITableView (its named as "Table View") to our Layout.

You can seed default Table View's layout



PHASE - III

It's time to Write some code..

So let's begin for AppDelegate (App's startup point), we need to define which is our Startup Screen (View Controller) on this app.

1. Okay, Open the AppDelegate.h file

1.1  Add @class directive just below to #import statement

@class MYViewController;

1.2 then add property for it (below to UIWindow's property)

@property (nonatomic, strong) MYViewController *myViewController;

Finally our AppDelegate.h file look like this


-----------------------------------------------------------------------------------------------------------------------------------------

//
//  AppDelegate.h
//  TableViewDemo
//
//  Created by RDC on 2/27/13.
//  Copyright (c) 2013 RDCWorld. All rights reserved.
//

#import <UIKit/UIKit.h>

@class MYViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) MYViewController *myViewController;

@end

-----------------------------------------------------------------------------------------------------------------------------------------

2. Now come to the AppDelegate.m file (double click on it to open)

2.1 add #import "MYViewController.h" 
2.2 now we need to synthesize MyViewController's property what we defined in .h file.
so just add below code after @implementation

@synthesize myViewController;

2.3 in didFinishLaunchingWithOptions method.

delete below line

self.window.backgroundColor = [UIColor whiteColor];

and replace with given code lines

myViewController = [[MYViewController alloc] init];
self.window.rootViewController = myViewController;


That's it Save the code now!!

So Finally our AppDelegate.m file look like this.

-----------------------------------------------------------------------------------------------------------------------------------------

//
//  AppDelegate.m
//  TableViewDemo
//
//  Created by RDC on 2/27/13.
//  Copyright (c) 2013 RDCWorld. All rights reserved.
//

#import "AppDelegate.h"
#import "MYViewController.h"

@implementation AppDelegate

@synthesize myViewController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    myViewController = [[MYViewController alloc] init];
    self.window.rootViewController = myViewController;
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


-----------------------------------------------------------------------------------------------------------------------------------------


For this time if you will execute application you can See blank table on your screen.




Now is the main Task.

We will implement table view's delegate and datasource's methods
* to put data on table view
* to create table cell,no of rows etc.

Let's make it simple as we can.

First is First!! open header file (MyViewController.h)

1. define UITableView's delegate and datasource 

<UITableViewDelegate,UITableViewDataSource>

2. create one NSMutableArray (give name as "myFavMusicList")to store our 
favorite music list (we will show in table view).

@property (nonatomic, retain) NSMutableArray *myFavMusicList;


So Make sure Finally we have our MyViewController.h file code like this


-----------------------------------------------------------------------------------------------------------------------------------------

///
//  MYViewController.h
//  TableViewDemo
//
//  Created by RDC on 2/27/13.
//  Copyright (c) 2013 RDCWorld. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MYViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, retain) NSMutableArray *myFavMusicList;


@end


-----------------------------------------------------------------------------------------------------------------------------------------

Now Come to the Heart of the application.

Open Implementation (ViewController.m ) file

1. synthesize the favMusicList array after just @implementation

@synthesize myFavMusicList;

2. in viewDidLoad method 

2.1 initialize array 

 myFavMusicList = [[NSMutableArray alloc]init];

2.2 then add the values

    [myFavMusicList addObject:@"Boulevard of broken dreams"];
    [myFavMusicList addObject:@"We Will Rock You"];
    [myFavMusicList addObject:@"Stairway To Heaven"];
    [myFavMusicList addObject:@"Rang De Basanti"];
    [myFavMusicList addObject:@"We are the champions"];
    [myFavMusicList addObject:@"Nothing Else Matters"];
    [myFavMusicList addObject:@"Wake Me Up When September Ends"];
    [myFavMusicList addObject:@"Crawling in my skin"];
    [myFavMusicList addObject:@"Summer of '69"];
    [myFavMusicList addObject:@"Temple Of The King"];


3. Final code..

to make table alive, mainly Two method always required

numberOfRowsInSection : how many rows in our table
cellForRowAtIndexPath : create the table's cell or put the data on rows

3.1 so add the "numberOfRowsInSection" method code just before @end


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


3.2 now create the cell for every row in our table in "cellForRowAtIndexPath"


-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"tableCell";
    
    UITableViewCell *cell;
    
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];    
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    
    NSString *musicLabel = [myFavMusicList objectAtIndex:indexPath.row];
    cell.textLabel.text = musicLabel;
    return cell;    
    
}


That's perfect!!

Finally our MyViewController.m file look like 

-----------------------------------------------------------------------------------------------------------------------------------------

//
//  MYViewController.m
//  TableViewDemo
//
//  Created by RDC on 2/27/13.
//  Copyright (c) 2013 RDCWorld. All rights reserved.
//

#import "MYViewController.h"

@interface MYViewController ()
@end

@implementation MYViewController

@synthesize myFavMusicList;

- (void)viewDidLoad
{
    [super viewDidLoad];
    //initilize array
    myFavMusicList = [[NSMutableArray alloc]init];
    
    //add values
    [myFavMusicList addObject:@"Boulevard of broken dreams"];
    [myFavMusicList addObject:@"We Will Rock You"];
    [myFavMusicList addObject:@"Stairway To Heaven"];
    [myFavMusicList addObject:@"Rang De Basanti"];
    [myFavMusicList addObject:@"We are the champions"];
    [myFavMusicList addObject:@"Nothing Else Matters"];
    [myFavMusicList addObject:@"Wake Me Up When September Ends"];
    [myFavMusicList addObject:@"Crawling in my skin"];
    [myFavMusicList addObject:@"Summer of '69"];
    [myFavMusicList addObject:@"Temple Of The King"];        
}

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

#pragma mark - UITableView's Delegate and Datasource methods
//data source 

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

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *cellIdentifier = @"tableCell";
    
    UITableViewCell *cell;    
    cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];    
    
    //we will re-use our cell, while scrolling table
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];        
    }
    
    NSString *musicLabel = [myFavMusicList objectAtIndex:indexPath.row];
    cell.textLabel.text = musicLabel;
    return cell;    
    
}

@end

-----------------------------------------------------------------------------------------------------------------------------------------


PHASE - IV

Now we need to hookup below items to our application's File Owner

i . UITableViewDelegate
ii . UITableViewDataSource


 First we will hook-up UITableView's data source & delegate to its File Owner.

1.1  Open MyViewController.xib file
1.2 Select UITableView on Layout
1.3 Select Connection Inspector in Top Right side (as shown in below picture)
1.4 now click on (+) for data source (its also on Top right side) and drag cursor to File Owner ( Yellow Box on Left side).



Now do the same for delegate also. If you on the right way and did it well you can see Connection Inspector property look like




PHASE - V

It's time to wrap it up. So let's Save application and Run it.

Here is the output screen shot.



Wooooh!! we did it. Table View is the on of Important part in iOS app development.
We learn it.

You can download complete application source code zip file here : TableViewDemo

I would love to here your thought!!

No comments:

Post a Comment