Friday, April 8, 2011

Creating a Custom TableView cell in iPhone

In this post we shall have a look on how to create a custom cell for the table view.

Design view: For this demo we shall make a custom cell with three labels and one image view, the three labels will represent details about a particular cartoon character including an image view which will show the image of that cartoon character, here’s a view at the final output.





Step 1: Open Xcode and select the windows based application template and add the UITableViewController subclass file to the project with the name mytableviewController or any other name of your choice. Now their will be two files that would be added into your project those are the mytableviewController.h and mytableviewController.m file. Now add a UITableViewCell subclass file to your project with the name mycustonmcell and two more file will be added with the name mycustomcell.h and mycustomcell.m.




Step 2: Select the mycustomcell.h file and declare three variables of UILabel type and one variable of UIImageView type, Also declare the properties of these variables that you will be using (we are declaring proprities so that we can access these variables with the help of the dot operator in the mytableviewController.m file). Here’s the code to do that.

#import <UIKit/UIKit.h>
@interface mycustomCell : UITableViewCell {

UILabel *charName,*cartoonName,*charCity;
UIImageView *charImage;
}
@property (nonatomic,retain) UILabel *charName,*cartoonName,*charCity;
@property (nonatomic,retain) UIImageView *charImage;
@end


Step 3: In the mycustomcell.m file give memory to these variables

#import "mycustomCell.h"
@implementation mycustomCell
@synthesize charCity,charName,charImage,cartoonName;

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
        // Initialization code
charName = [[UILabel alloc]initWithFrame:CGRectMake(102, 14, 85, 21)];
  charName.font = [UIFont fontWithName:@"Verdana" size:12.0f];
   
    cartoonName = [[UILabel alloc]initWithFrame:CGRectMake(102, 40, 111,21)];
    cartoonName.font = [UIFont fontWithName:@"Verdana" size:12.0f];
  charCity = [[UILabel alloc]initWithFrame:CGRectMake(102, 65, 81, 21)];
  charCity.font = [UIFont fontWithName:@"Verdana" size:12.0f];
charImage = [[UIImageView alloc]initWithFrame:CGRectMake(7, 12, 78, 70)];
//adding the controls in the table cell
[self.contentView addSubview:charName];
[self.contentView addSubview:cartoonName];
[self.contentView addSubview:charCity];
[self.contentView addSubview:charImage];
    }
    return self;
}



Now after giving memory to the variables and setting the frame of the variables its time to add this custom cell to our table view so in order to do that first you have to import the mycustomcell.h as the header in the mytableviewController.h file

#import <UIKit/UIKit.h>
#import "mycustomCell.h"


@interface mytableviewController : UITableViewController {

}

@end


and then in the mytableviewController.m file go to the

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {


here all you have to do is replace the below code 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }


With this code

 mycustomCell *cell = (mycustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[mycustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

and then using switch case manipulate the cells

switch (indexPath.row) {
case 0:
cell.cartoonName.text = @"Dragon ball z";
cell.charName.text = @"Goku";
cell.charCity.text= @"Japan";
cell.charImage.image = [UIImage imageNamed:@"goku.jpg"];
break;
case 1:
cell.cartoonName.text = @"Batman ";
cell.charName.text = @"Bruce Wyane";
cell.charCity.text= @"Gotham City";
cell.charImage.image = [UIImage imageNamed:@"batman4952.jpg"];
break;
case 2:
cell.cartoonName.text = @"Superman";
cell.charName.text = @"Clark Kent";
cell.charCity.text= @"Krypton";
cell.charImage.image = [UIImage imageNamed:@"superman.jpg"];
break;
case 3:
cell.cartoonName.text = @"Spider man";
cell.charName.text = @"Peter Parker";
cell.charCity.text= @"NewYork";
cell.charImage.image = [UIImage imageNamed:@"Spider-Man.jpg"];
break;
case 4:
cell.cartoonName.text = @"Iron Man";
cell.charName.text = @"Tony Stark";
cell.charCity.text= @"U.S.A";
cell.charImage.image = [UIImage imageNamed:@"ironman.jpg"];
break;
}



Step 4: The above code is self explanatory,by using switch case operator i have given different names and images to different cell of my table view, and one more important thing that i forgot to mention is that we have to increase the row height of our table view so for that use the delegate method given below

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 90;
}

Step 5: Select the appdelegate.m file of your project and add this piece of code and then run your application to get the output just like the above image

#import "CustomCelldemoAppDelegate.h"
#import "mytableviewController.h"

@implementation CustomCelldemoAppDelegate

@synthesize window;


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

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

After adding this select build and go and get the below output



i hope this post has helped you in understanding how to create a custom table cell for your application, your comments are valuable positive or negative, until then happy iCoding and have a great Day.

8 comments:

  1. This article is really nice one.. one more method of tableview customization is there by using Layout subview.

    ReplyDelete
  2. Thank You so much .. very helpful ,
    i hope if you make it with image pulled from xml .

    regards.

    ReplyDelete
  3. @Abdulrahman: well if you want the images parsed from the xml file then in that case what you can do is refer to some of my tutorials on how to parse an xml file and display the image from the server here's a link to that

    GData XML Parser:

    http://iphonebyradix.blogspot.com/2011/03/using-gdata-to-parse-xml-file.html


    Load Image from server:

    http://iphonebyradix.blogspot.com/2010/12/load-image-from-server-in-imageview.html

    The data in the xml file would be the link to the image present in some server or some images present in bundle. Try this out if it dosent work then let me know will mail you a sample code for doing this....

    ReplyDelete
  4. Can you put the source code in zip format.

    ReplyDelete
  5. Hi radix
    I am new to iOS development. I am using Xcode4.5. i tried to customize table view as you said except that i used UITableView on UIView Controllers. When i try to instantiate cutometablecell class it throws an exception "TReceiver 'custometablecell' for class message is a forward declaration". How can i rectify this????

    Pls help me..

    Thanks in advcance

    ReplyDelete