The
post here sums up my experience in creating a custom cell in iPhone
UITableView. In fact I was searching for a way to create a custom
cells displaying couple of text contents and images. I tried with the
default textlabel and deatailtextlabel to display text and it worked
fine too. But I was fried up when I was in need for some more labels.
This made me google more and finally I came up with what I wanted.
Thats it for the intro.
Here
goes the flow I used..
- Add a new Objective C class with subclass of UITableViewCell to your project. Here I name the class as CustomCell.
- This automatically adds a pair of classes the .h and .m class.
- Now add new View XIB file to project. Replace the view file with UITableViewCell control from your library .
- Now set an identifier to the cell here I name it MyCell.
- Map the class identity to your objective c class you added before.
Now you can open
your XIB and start designing the custom cell.Here I add a view
and on that I drag and drop the needed controls from the library.
And now map the controls, which looks like below after mapping.
Now Lets stop designing and
start code. Declare the Outlets for the controls added in the custom
cell class. Never forget to synthesize those in .m file as that is a
standard way of coding objective c with Xcode.
So
here is it our custom cell is ready to get merged with the
UITableView in our project. As our first step here import the header
file ("CustomCell.h") to
the controller class where we have a table to which we integrate our
custom cell.
Its
all about the cellForRowAtIndexPath: where
we actually code to merge the "MyCell" to the
table, numberOfRowsInSection: were
we specify the number of cells to be displayed .
Now
enter the following codes to CellForRowAtIndexPath
-
(NSInteger)tableView:(UITableView
*)tableView numberOfRowsInSection:(NSInteger)section
{
//
Return the number of rows in the section.
return
6;
}
-
(UITableViewCell
*)tableView:(UITableView
*)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
{
static
NSString
*CellID = @"MyCell";
//Should
match the identifier of custom Cell
CustomCell
*cell = (CustomCell*)
[tableView dequeueReusableCellWithIdentifier:CellID];
if
(cell == nil)
{
NSLog(@"New
Cell Made");
NSArray
*topLevelObjects = [[NSBundle
mainBundle]
loadNibNamed:@"CustomCell"
owner:nil
options:nil];
for(id
currentObject in
topLevelObjects)
{
if([currentObject
isKindOfClass:[CustomCell
class]])
{
cell
= (CustomCell
*)currentObject;
break;
}
}
}
[[cell
Name]
setText:@"Head
First IPhone Development"];
[[cell
Author]
setText:@"Tracey
Pilone, Dan Pilone"];
[[cell
Price]
setText:@"English"];
[[cell
imageView]
setImage:[UIImage
imageNamed:@"HeadFirst.jpg"]];
return
cell;
}
compile
and execute. The output appears as below .
This is all what I
have done. Hope this post helped you in some ways. Keep tuned and
await for my next post on 'Managing the selection of cells'.
Thank you ...happy blogging :)
Thank you ...happy blogging :)