Saturday, March 19, 2011

A Simple UITableView tutorial

In this tutorial we will learn how to implement a list view called UITableView on iOS and also how to add your own custom cell to it to give it a whole new look unlike default table view provided by iOS.
The best part is that we'll make this table in our on view based application and not using any of the templates provided by iOS.

So Lets get started!

Step1- Open Xcode and on the left choose iphone application>view based application.Lets name it as UITableViewSampleViewController click next.
Now open UITableViewSampleViewControllerViewController.xib and add a UITableView to your main view and your nib will look as follows......

Step 2- Now go to your UITableViewSampleViewControllerViewController.h file and now you need to declare a IBOutlet of your table view in your .h file.so replace your
UITableViewSampleViewControllerViewController.h file with the following code snippet.


#import <UIKit/UIKit.h>

@interface UITableViewSampleViewControllerViewController : UIViewController {
    IBOutlet UITableView *sampleTableView;
}
@property(nonatomic, retain) IBOutlet UITableView *sampleTableView;

@end

and synthesize this property in your .m file of the same by writing the following statement in your .m file just below @implementation

@synthesize sampleTableView

what we did here is tell our view in xib that hey there is a IBOutlet of the table view in your controller file and @synthesize automatically generates getter and setter for the same.

Step 3-The next step is to link the outlet we just created with the table view which we had put in our xib file. So now open  UITableViewSampleViewControllerViewController.xib and link the table view to the outlet in file owner as follows-


and delegate and datasource as follows--


Thats all in the nib.

Step 4 - Now lets implement the delgates of our table view in our view controller files.
Now we linked the delegate and datasource of our table view to our file owner but we need to tell our view controller that he's gonna implement these delegates by adding the following bold statements in our .h file first.
#import <UIKit/UIKit.h>

@interface UITableViewSampleViewControllerViewController : UIViewController <UITableViewDelegate,UITableViewDataSource> {
    IBOutlet UITableView *sampleTableView;
}
@property(nonatomic, retain) IBOutlet UITableView *sampleTableView;

@end

Now we need to implement the delegate methods for our sampleTableView in our .m file.Delegate methods define the properties of the object which they are related to. By properties  I mean the whole functionality.
Just compile your code before proceeding forward.And if you get any errors then please go through again you might have missed out something.

So now add the following 4 delegate methods in your UITableViewSampleViewControllerViewController.m file any where between @implementation and @end. For now we'll have 1 section and 20 rows in our sampleTableView.

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


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return 20;
}


// 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] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"row %i",[indexPath row]];
    // Configure the cell...
   
    return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  
}

Just Build and Run your code and you should see something like this.



Step 5 -For that we need to add a new file. right click on the classes folder and select Add New File option Select objective c class and UITableViewCell . Click next name it as SampleTableViewCell.m and make sure that also generate .h is checked. click choose and two new files will be created in you classes folder.


Also add a xib file of this cell same right click on your resource folder and add a new empty xib file and name it as same as your table cell file.In this case as SampleTableViewCell.check iphone.


Now open SampleTableViewCell.xib and add a UITableViewCell from library to your empty xib it should look as follows.


Now to this label add a UIView from your library, a label and a ImageView and your cell will look something like - and make sure that the view dimensions and the table cell dimensions and x y are same. alos resixe image view and label according to your requirement.


Also Make sure that class which your this tableviewcell is extending is SampleTableViewCell just open the inspector and change the class as follows.





Step 6 - Now lets go and make outlets for these imageview,label and view that we added to our xib in our SampleTableViewCell.h. Add replace the code in your SampleTableViewCell.h with the following

#import <UIKit/UIKit.h>


@interface SampleTableViewCell : UITableViewCell {
    IBOutlet UIView *cellBackgroundView;
    IBOutlet UILabel *titleLabel;
    IBOutlet UIImageView *cellImage;
}
@property(nonatomic, retain) IBOutlet UIView *cellBackgroundView;
@property(nonatomic, retain) IBOutlet UILabel *titleLabel;
@property(nonatomic, retain) IBOutlet UIImageView *cellImage;
@end

and synthesize the same in your .m file by adding this line below @implementation
@synthesize cellBackgroundView,titleLabel,cellImage;

Step 7 - Next is the linking process of these outlets in our xib. Open your SampleTableViewCell.xib and link the outlets as follows. Be careful that now you dont have to connect your outlets to your FileOwner but to your tableView cell because it is only extending your SampleTableViewCell class.






Step 8 - Phew!!Now our cell is up and ready to be included in our table cell.Just go to UITableViewSampleViewController.m file and replace the code in cellForRowAtIndexPath method with the following code.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";   
    SampleTableViewCell *cell=(SampleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
    if(cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"SampleTableViewCell" owner:self options:nil];
        for (id oneObject in nib)
            if ([oneObject isKindOfClass:[SampleTableViewCell class]])
                cell=(SampleTableViewCell *)oneObject;
    }
   
    // Configure the cell...
    cell.titleLabel.text = [NSString stringWithFormat:@"row %i",[indexPath row]];
    cell.cellImage.image = [UIImage imageNamed:@"normal.jpg"];
    cell.cellBackgroundView.backgroundColor = [UIColor grayColor];
    return cell;
}
make sure that you import SampleTableViewCell.h file in this file. and for imageview you need to add a image to your resource folder just drag and drop any image and check copy items into destination folder box so that that image is automatically added to your project folder.
Note: Just open your Tableview controller xib and make the row height same as your table cell. otherwise your cells will overlap each other.
Thats all we're done The final output should look as follows .. in our next tutorial we'll learn how to perform an action on selection of a row in this tableview.


Ok goodbye Happy Coding!!!!