Customise UITableView Subclass Cell? - iphone

I have made my custom cell in Interface Builder and created a custom UITableViewCell class for it, but when its loaded in no changes are made to it. I have this code in the custom class:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self)
{
// Initialization code
//Get the wedding date and display it
myLabel.text = #"Hello";
}
return self;
}
myLabel has been declared in the header, has a property and has been linked in Interface builder, but when I run the app and see my table, I don't get my 'Hello' text. Any ideas?
Thanks.
EDIT:
I am not using a nib file, I have it in a UITableViewController within my Storyboard. Plus, here is the cellForRowAtIndexPath code below, I simply have an array filled with the required cell identifiers and then creates said arrays:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier;
for (int cell = 0; cell <= [tableCellsArray count]; cell++)
{
if ([indexPath row] == cell)
{
CellIdentifier = [tableCellsArray objectAtIndex:cell];
}
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
return cell;
}

How do you create your cell ? Do you load it from a Nib or you allocate it ?
If you allocate it, you need to properly initialize your instance fieds (e.g. myLabel).
If you load the cell from a nib, i fear
(id) initWithCoder:(NSCoder *)aDecoder
is the init method you want to override.
Anyway, you could just put a breakpoint to make sure you pass through there and print myLabel to make sure it's correctly initialized.
-- Edit
If you want to have a customized cell view using a nib, you cannot initialize your cell view using initWithStyle:reuseIdentifier: method.
Using initWithStyle:reuseIdentifier: means you will initialize all your view by your own implementation (e.g. you will allocate, initialize and configure all you views, it won't use the xib file)
If you want to use a xib file, you need to use loadNibNamed:owner:options: method in NSBundle.
Typically, i've seen two implementations :
[[NSBundle mainBundle] loadNibNamed:#"" owner:self options:nil];
In this implementation, you load your xib giving the UIViewController subclass as an owner. In the xib, make sure the File Owner class is your UIViewController subclass. Then just link the cell with a property of your UIViewController subclass and calling loadNibNamed:owner:options: will just allocate and initialize a new cell view which will be available in the property of you UIViewController subclass. This is what the Apple Documentation advise you to do.
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:#"" owner:nil options:nil];
UITableViewCell myCustomCell = [nibObjects objectAtIndex:0];
In this implementation, you don't pass any owner to the xib file and get the object you want. Just makes sure your xib file only has one object which is the cell view. I prefer this approach as i think it's "weird" to have a property for cell creation but you need to make sure that the content of your xib file will keep your custom cell view at the 0 index.
Whatever method you pick, remember that loading a xib will call
initWithCoder:
instead of
initWithStyle:reuseIdentifier:
Finally, i advise you to go take a look at Aadhira's link to the Apple documentation which explain with exemple how to use custom UITableCellView with a xib file.

Go though the Apple documentation , which describes about customizing UITableViewCell.
In the above page, pl. see Listing 5-5 Loading a cell from a nib file and assigning it content, which describes clearly on customizing cell with nib file.

Related

Use XIB from parent class in UITableViewCell

Currently I have a newsfeed with custom UITableViewCells such as :
NewsCell.m
NewsCell.xib
NewsCell_Friends.m
NewsCell_Friends.xib
NewsCell_CheckinPhoto.m
NewsCell_CheckinPhoto.xib
[...]
NewsCell_Friends and NewsCell_Checkin inherit both from NewsCell (methods and elements such as titleLabel, dateLabel that are shared by all subclasses)
At the moment, I have never used NewsCell class itself and only subclasses as each kind of news has a very distinct layout (Xib).
Let's say now that, I would like to have a light implementation in terms of UI of my newsfeed where all cells have the same appearance, same height, same content : the titleLabel and the dateLabel.
(Such as a notification feed in fact).
What I would like to do is to reuse NewsCell.xib as a standalone for every type of news, e.g. below :
NewsCell_CheckinPhoto *cell = [tableView dequeueReusableCellWithIdentifier:#"CheckinPhoto"];
if (!cell){
UIViewController *c = [[UIViewController alloc] initWithNibName:#"NewsCell" bundle:nil];
cell = (NewsCell_CheckinPhoto *)c.view;
cell.parent = self;
}
[cell configureCell:indexPath withNews:news];
return cell;
in the cellForRowAtIndexPath delegate methods.
Notice that I use the NewsCell xib and not the NewsCell_CheckinPhoto xib in this controller.
But it is not working :the nib file is well loaded and the content of the NewsCell.xib well displayed in the cell, BUT the configuration of the labels (e.g, titleLabel.text = #"Robert took a photo") within the NewsCell_CheckinPhoto class is neither working nor even called.
It works only if I specify class type *NewsCell_CheckinPhoto* in the NewsCell.xib file , but that would not allow me to reuse NewsCell.xib for rendering each subclasses of NewsCell with a sample and unique representation.
When I understand you correct you want to load a cell from a XIB.
You should not do it with
UIViewController *c = [[UIViewController alloc] initWithNibName:#"NewsCell" bundle:nil];
but put only the cell in the XIB and then load it with
UITableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:#"NewsCell"][0];
or similar (please check docs).
Also keep in mind when you load something like a table view cell from a XIB, it is initialised with initWithCoder:, not init, or initWithFrame:. This might be the reason, why your outlets are not intialised.

How to control a customized UITableViewCell within a UITableView Implemented within a UIViewController?

In my app I wish to have a UIViewController that will hold a UITableView in it. In this UITableView I wish to have a customized UITableViewCell (i.e. I wish to define my own elements in this CELL - image, labels and buttons - as seen in the image below). And... I want to create them in the Storyboard.
Now, setting the elements in the Storyboard is easy.
I understand how to connect the UITableView and set it in the UIViewController (including the delegates in the .h file and using the basic table delegate methods).
What I'm not clear about, is how to connect and control the customized UITableViewCell and its outlets. Can I create the Outlets and Actions within the UIViewController .h and .m files? Do I need to create a separated UITableViewCell.h/.m files and call on them in the cellForRowAtIndexPath method?
Can anyone suggest what's the best approach for my needs?
UPDATE:
Here is the code I used in cellForRowAtIndexPath while using the separated MyCell.h/m file option. This code is written in the ViewController.m file, where the UITableView is implemented.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ContentCell";
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//MyCell is the Objective-C Class I created to manage the table cells attributes.
//#"ContentCell" is what I had entered in the Storyboard>>UITableViewCell as the Cell Identifier.
if (cell == nil) {
cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//Here is the place I'm not clear about - Am I supposed to init the cell in a different way? If so, how?
}
cell.contentNameLabel.text = [self.dataArray objectAtIndex: [indexPath row]];
// this is the test I had done to check if the new "MyCell" object is actually getting what I would expect it to get. well... the text gets updated in the relevant label, so i guess it gets it
return cell;
}
When running the app, using the debugger break point, I can see that the code always skips the "if (cell == nil)" and never enters the code where the new MyCell object supposes to be allocated and initiated. Any idea what may I be doing wrong?
Correct, create separate UITableViewCell.h/.m files to match your custom UITableViewCell class and call on them in your cellForRowAtIndexPath method.
In your storyboard, set the class of your custom UITableViewCell to your custom class (e.g. CustomTableCell).
Your custom UITableViewCell class would contain IBOutlets which you would wire up in your storyboard, here is an example:
CustomTableCell.h:
#import "CustomStuff.h" // A custom data class, for this example
#interface CustomTableCell : UITableViewCell
#property (nonatomic, weak) IBOutlet UILabel *titleLabel;
- (void)configureForCustomStuff:(CustomStuff *)stuff;
#end
CustomTableCell.m:
#import "CustomTableCell.h"
#implementation CustomTableCell
#synthesize titleLabel;
#pragma mark - Configure the table view cell
- (void)configureForCustomStuff:(CustomStuff *)stuff
{
// Set your outlets here, e.g.
self.titleLabel.text = stuff.title;
}
#end
Then, in your cellForRowAtIndexPath method, configure your cell:
CustomTableCell *cell = (CustomTableCell *)[tableView dequeueReusableCellWithIdentifier:#"CustomCellID"];
// Your custom data here
CustomStuff *customStuff = <YOUR CUSTOM STUFF>
[cell configureForCustomStuff:customStuff];

How to display a complex UIViewController inside another UIView Controller?

Ok, so here's the situation. I currently have a view controller called MainViewController which has a UITableView with many different cells. When I click on a cell, I want that cell to expand (grow in height) and show some "additional information". The problem is, this additional information is very complex and can contain UILabels, other UITableViews, UIWebViews and UIImageViews. Furthermore, this "additional data" requires quite a bit of computation in order to determine what exactly to display (i.e. what the UILabels say, how large the UIImageViews are). Therefore, because of the complexity of this "additional information", I'm at a loss as to how to design my program.
The "additional information" requires a lot of code, thus I don't want to just throw that code into the MainViewController. Additionally, it would be nice if there was some way to use Interface Builder to design these "additional information" views graphically rather than programatically.
Currently I have each set of additional information as its own separate UIViewController (thus allowing me to have separate classes for the data and allowing me to use interface builder) and I just segue to a new screen when a cell is selected. However, I don't want to segue to a new screen; I want all of the data that this UIView controller is showing to be shown in MainViewController. What's the best way to do this?
In summary, I currently have one UIViewController segueing to another UIViewController; however, I want the second UIViewController's content to be show in the first. If possible I would like to use some sort of Interface Builder and to separate out the logic for this second UIViewController into another class.
Details:
~ I'm developing for iOS 5 only and I'm using ARC.
~ I've never developed for iOS 4 or below before and I have never used nib files before but I would be willing to learn if required. Simple sample code would be helpful.
~ Thanks!
Same opinion as SmartWork.
You should create your custom UITableViewCell class with its xib file, with a UITableViewCell as main xib view
And in your tableView datasource, you can import it as below :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"MyViewCell";
MyViewCell *cell = (MyViewCell *)[self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"MyViewCell" owner:nil options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (MyViewCell *)currentObject;
break;
}
}
}
[self configureCell:cell atIndexPath:indexPath]; // your own function to customize your cell.
return cell;
}
Then, in the cell xib, you can set the max height of the cell, and decide the effective height in the UITableViewDelegate class.
There are some good suggestions here, but note that loadNibNamed:owner: is a fairly expensive API to call repeatedly because it reads the nib from the filesystem each time. Instead, consider doing something like this.
Register your nib file in viewDidLoad. In Interface Builder, make sure to provide a reuse identifier for your custom cell.
- (void)viewDidLoad
{
[super viewDidLoad];
UINib *myNib = [UINib nibWithNibName:#"MyNib" bundle:nil];
[self.tableView registerNib:myNib forCellReuseIdentifier:#"MyCell"];
// Do any other stuff you need to do...
}
Then just dequeue your custom cell whenever you need it. UINib will cache the nib file in memory to avoid reloading it from the filesystem each time.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
// Configure cell as needed...
return cell;
}
in my opinion there is no need of using one UiviewController inside another.
u can use Uiview with nib file so u can design these "additional information" views graphically. its very easy to implement and maintain it.
Just to add to what SmartWork said, when you tap a particular cell, you can update the height of that row using the following lines of code:
- (CGFloat)tableView:(UITableView *)aTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// set a dynamic value for the cell height depending on the state of the data in the cell
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// update the state of the data in the cells here..
// calling these below lines will change the height of the cells smoothly
[tableView beginUpdates];
[tableView endUpdates];
}
You will also need custom UITableViewCells. Look at them as simple views and add and remove any number of subviews that you need
If you are keen on using Nibs for your subviews inside the cells, you can create their nibs and connect them to your Custom TableView Cells as follows: (The subviews can be properties of your tableViewCell)
NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:#"MyTableViewCellNib" owner:self options:nil];
mySubview = [(SubView *)[nib objectAtIndex:0]retain];

UITableViewCell from a custom .XIB file doesn't create outlets

Update 2:
Long story short, I was being silly (and, in my defense, not properly educated) about this. It works now. My questions have derailed from the original topic a little bit, but that's because I wasn't understanding what was going on in my application. I would like to close the question with one last (and small) query:
I've got two labels in my customCell.xib. I want one of them (cell.label2) to sometimes contain a longer segment of text (2-3 lines). I know one way to make it all fit is to set the autoshrink property, but that shrinks to the text so it can fit on a single line. I want to preserve the original text size and expand the cell's height instead, making the text span multiple lines instead of shrinking it.
Is there a way to do this?
Update 1:
I tried a few things based on the replies below, and they got me nowhere. I am growing convinced that I am doing something fundamentally wrong, and you guys just can't think of it because it's so basic. So let's try again. I am going to changed the names a little, so they are easier to remember.
The problem seems to be in the fact that I can't create any IBOutlets or IBActions for my customCell. Right now I have 3 files that should handle this (DetailedDirectionViewCell.{h,m,xib}, but the Interface Builder doesn't allow me to create a property/outlet/reference out of my UITableViewCell object - anywhere.
Instead of copying the code here, I've provided a PasteBin entry with links to my code. As before, I've removed the less interesting methods. Take a look if you will.
http://pastebin.com/p4eADhKQ
I also have customCell.{h,m}, but those are just new Objective C class files that inherit from UITableViewCell. customCell.xib is just a cell with two labels.
So I have a couple of problems really.
First, generating a UITableView programmatically, using a custom UITableViewCell contained in a .XIB file of its own. My DirectionsViewController class is just a UITableView with programmatic cells. Tapping on one of the cells needs to present a DetailedDirectionsViewController table (in a modal way), the cell design for which sits in a DetailedDirectionsViewCell.xib file. The problem is, I can't create an IBOutlet for the UITableViewCell from the nib file - anywhere. Dragging the File's Owner icon/outlet doesn't offer to create anything. Which, after 5 hours of struggling, means that I can't present my detailed view.
The second problem involves adding a navigation bar to the DirectionsViewController, but let's leave that alone for now.
Here are some methods you might find helpful:
//inside DirectionsViewController
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)
{
DetailedDirectionsViewController *vc = [[DetailedDirectionsViewController alloc] initWithStyle:UITableViewStyleGrouped];
vc.instruction = [turnList objectAtIndexPath:indexPath.row];
[self.tabBarController presentModalViewController:vc animated:YES];
}
//inside DetailedDirectionsViewController
- (UITableViewCell *) tableView:(UITableView *) cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"directionsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
[[NSBundle mainBundle] initWIthNibNamed:#"DetailedDirectionsViewCell" owner:nil options:nil];
cell = self.tableViewCell;
self.tableViewCell = nil;
}
//here I configure the custom cell
return cell;
}
I don't think the rest of the methods are of interest, because they are either working as expected, or are pretty much the default ones.
To sum up:
DirectionsViewController - essentially a UITableViewController with custom cells. No .xib file
DetailedDirectionsViewController - detailed information about the entries from DirectionsViewController. Cells here should come from a .XIB file, but that's broken.
DetailedDirectionsViewCell - this is the custom cell. I can't set its File's Owner.
Ok.. You do not create IBOutlet connection from File's Owner. Have a look at a screenshot. You create IBOutlet from CustomCell's view(with Red Arrow).
Looking after your code just follow these steps.
1) Goto CustomCell.h file. As you are saying customCell.xib has two UILabels(assume label1 & label2) you gonna have to declare properties and create outlets in CustomCell.h file and in .m file synthesize and release it. Refer this code screen of mine.
2) Now in CustomCell.xib, select view of CustomCell not File's Owner(File's Owner should inherit from NSObjectonly) go to Identity Inspector(Marked with Red Ellipse) and select the corresponding Customcell class (marked with Red rectangle).
3) Right click your customcell's view and make connections to labels. And save it..
4) In your DirectionsViewController.m you have this UITableView's delegate method cellForRowAtIndexPath. Change it like this :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CustomCellIdentifier = #"CustomCell";
EditProjectCustomCell *cell = (EditProjectCustomCell *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier]; // typecast to customcell
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"EditProjectCustomCell" owner:self options:nil];
for (id oneObject in nib)
if ([oneObject isKindOfClass:[EditProjectCustomCell class]])
cell = (EditProjectCustomCell *)oneObject;
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
}
cell.label1.text=[someArray1 ObjectAtIndexPath: indexPath.row];
cell.label2.text=[someArray2 ObjectAtIndexPath: indexPath.row];
return cell;
}
this delegate method is gonna be called as many times as you returned value in numberOfRowsInSection DataSource method. Every time cell.label will be blank and you will add data to label by calling this line. so no need to create label each time as you did between line 79-90 here. http://pastebin.com/Vd4PKjTu
cell.label1.text=[someArray ObjectAtIndexPath: indexPath.row];
Creating custom cell means you create UI(i.e. .xib),interface & implementation (.h,.m file) for UITableViewCell by yourself and adopt them in your class's (i.e. DirectionsViewController.m) cellForRowAtIndexPath delegate method.
To load a custom cell, I've used this code (test it and it's working)
static NSString *CustomCellIdentifier = #"CustomCommentIdentifier";
detailedDirectionsViewCell *cell = (DetailedDirectionsViewCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"DetailedDirectionsViewCell" owner:self options:nil];
for (id oneObject in nib)
{
if ([oneObject isKindOfClass:[DetailedDirectionsViewCell class]])
{
cell = (DetailedDirectionsViewCell *)oneObject;
}
}
}
and make sure that you changed the cell class nib file as the following:
Click on the files owner, change the type of it to NSObject (this for not to confuse when connect the Outlets.
Remove any view you have in the nib file, then, drag and drop a UITableViewCell component.
Change the super class of the component to the Cell class, in your case, change the cell from UITableViewCell to DetailedDirectionsViewCell.
Connect the outlet.
This should work, let me know if you have any question.
To answer your last question in Update 2, did you consider using a text field instead of a label? You should be able to disable editing so the user can't change what is displayed. If you need it to be a label, in the Attributes Inspector for the label, there is a property called "Lines" under the "Label" drop down that you can adjust. I'm not sure how to access that property programmaticly, but a quick Google search should help you out there.
In my case I had two different views for one cell class. And when I connected outlets to .h file they were connected only to the first view representation, not the second.
So to ensure that your outlets are really connected go Xcode me menu and open View -> Utilities -> Show FileConnection inspector, then make sure that your view's outlets are really connected.

How to make a UITableViewCell with different subviews reusable?

I have a UITableView in which I display, naturally, UITableViewCells which are all of the same class, let's call it MyCell. So I have one MyCell.xib, one MyCell.h and one MyCell.m.
Unfortunately, this cells do contain one subview, which holds varying content, e.g. a train subview and a car subview. So if the UITableView is in need of a new cell, it's always a MyCell but sometimes it contains a train subview and sometimes a car subview.
Now, here is my problem: How to make MyCell properly reusable? The cell itself is reusable as intended (In the .xib I defined it's identifier) but it's subview has to be created again and again for every cell. My first idea was to change the identifier of MyCell depending on it's content but unfortunately, reuseIdentifier can't be changed on runtime.
I could, however, implement my own - (NSString *) reuseIdentifier {} which I guess would work, though I wouldn't consider it great style. Is there a better way to do this?
Many thanks in advance!
EDIT: I realize I need to add that the subviews are stored in their own classes/xibs to keep their code seperated.
Instead of adding subviews to cells I'd suggest that you create for every kind of cell your own class. If you have the kinds: train, car, bike, boat and airplane I would create five subclasses.
As I understand Apple the reuse mechanism with the identifier is just for that case: different types of cells get their own identifier, not every single cell a special one. Just to point how I interprete the whole thing.
In Apple's Table View Programming Guide for iOS / Characteristics of Cell Objects, the 3rd paragrpah delivers some insight into the meaning of the reuse identifier.
I've written myself a small TableViewCellFactory class which makes my life easier to create cells with the interface builder and have those in my app within minutes.
First of all a small example on how to use cellForRowAtIndexPath and the factory as well as setting content for a cell.
I create a fresh cell with the factory which needs the tableView so it can handle the reuse logic. Next thing is to let a method fill in the content for the cell. In this case it's a cell which shows a video clip with some text.
Data Source delegate method and helper
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)anIndexPath
{
VideoClipTableViewCell *cell = [TableViewCellFactory videoClipTableViewCellWithTableView:aTableView];
[self configureVideoClipCellWithCell:cell andIndexPath:anIndexPath];
// code to decide what kind of cell not shown, but it could be here, just move the model
// access code from the configure cell up here and decide on what you get
return cell;
}
Next comes the data source helper to put content into the cell. Get the content from my model array and set the properties. Note, this does everything by reference, nothing is returned.
- (void)configureVideoClipCellWithCell:(VideoClipTableViewCell *)aCell andIndexPath:(NSIndexPath *)anIndexPath
{
VideoClip *videoClip = [videoClips objectAtIndex:anIndexPath.row];
aCell.videoTitleLabel.text = videoClip.title;
aCell.dateLabel.text = videoClip.date;
// more data setting ...
}
TableViewFactory
This class consists mainly of convenience methods and some boilerplate methods to do the real work.
// Convenience static method to create a VideoClipTableViewCell
+ (VideoClipTableViewCell *)videoClipTableViewCellWithTableView:(UITableView *)aTableView
{
return [self loadCellWithName:#"VideoClipTableViewCell" tableView:aTableView];
}
// method to simplify cell loading
+ (id)loadCellWithName:(NSString *)aName tableView:(UITableView *)aTableView
{
return [self loadCellWithName:aName
className:aName
identifier:aName
tableView:aTableView];
}
// method with actually tries to create the cell
+ (id)loadCellWithName:(NSString *)aName
className:(NSString *)aClassName
identifier:(NSString *)anIdentifier
tableView:(UITableView *)aTableView
{
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:anIdentifier];
if (cell == nil) {
UINib * nib = [UINib nibWithNibName:aName bundle:nil];
NSArray * nibContent = nil;
nibContent = [nib instantiateWithOwner:nil options:nil];
for (id item in nibContent) {
if ([item isKindOfClass:NSClassFromString(aClassName)]) {
cell = item;
}
}
}
return cell;
}
I've thrown out the whole error and exception handling just to keep the example short. If someone is interested I'd add the code.
Some important things about the usage is:
The connected class name, the reuse
identifier and the nib name are all
the same so a cell can be created
with only one string constant, else
the long loadCellWithName has to be
used.
Don't forget to set the reuse identifier in interface builder.
The nib should contain only one TableViewCell (can be changed with some coding though)
Don't set outlets of the File's Owner, use those of the tableViewCell
Set the class identity of the cell to a corresponding class which should be created foremost
Look at the screenshot
Thoughts on subclassing own custom cells
It's actually easy to subclass your own cell, add a few properties to it, make them available in IB with outlets, choose the new extended class in IB for your nib file.
The main problem is interface itself. It's not easily done to have different kinds of cells based on a custom cell in interface builder. The first approach would be to copy the nib file, rename it and use it with all the existing references and link the new ones to differing outlets. But what happens if the base cell has to be changed? Going through all kinds of inheriting cells could be a tedious task.
I just stumbled across Custom views in Interface Builder using IBPlugins on Cocoa with Love. It's a nice tutorial how to extend the components Library in IB. Our custom base cell could become an item in the library and become the template we've been looking for. I think this approach is the right way to choose. Still, looking at necessary steps, it's not just done within 5 minutes.
Interface builder is a helpful tool, allowing us to rapidly create views, but when it comes to reusability through subclassing, there are big steps necessary to create maintainable views. A pity.
Creating the views with code only I think one is better off with subclassing if it comes to more than one level of inheritance or many ancestor classes for just one base view.
EDIT
On the other hand, Apple warns about excessive use of subviews in a cell:
However, if the content of a cell is
composed of more than three or four
subviews, scrolling performance might
suffer. In this case (and especially
if the cell is not editable), consider
drawing directly in one subview of the
cell’s content view. The gist of this
guideline is that, when implementing
custom table-view cells, be aware that
there is a tradeoff between optimal
scrolling performance and optimal
editing or reordering performance.
Right now any approach has its drawbacks and advantages:
Too man subviews will hit
performance, easily done with IB
Drawing with code will result in a
hard to maintain code base but will
perform better
Skipping IB makes
subclasssing of template cell classes
easier
Hierarchy through subclassing
difficult to achieve with IB with nib
files
There are a couple of different ways to do this. You need a way to access that subview and reset or change it on reuse.
You could subclass UITableViewCell with your own class of cell that has a property for the train or car view. That way you could access and change that view when the cell is reused.
Assign a different identifier to each type of cell:
`
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CarCellIdentifier = #"CarCell";
static NSString *TrainCellIdentifier = #"TrainCell";
if(indexPath == carCellNeeded) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CarCellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CarCellIdentifier] autorelease];
[cell addSubview:carView];
}
} else if(indexPath == trainCellNeeded){
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TrainCellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TrainCellIdentifier] autorelease];
[cell addSubview:trainView];
}
}
return cell;
}
Or assign a special tag to that sub view you are adding and when the cell comes back around again to be reused you can access that specific subview by its tag.
I would add both custom subviews to the nib and connect them to an outlet. And depending on the content I would hide one of them when you configure the content of your cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = /* load from nib */
}
if (/*indexPath conditionForTrainCell*/) {
cell.trainSubview.hidden = NO;
cell.carSubview.hidden = YES;
// configure train cell
}
else {
cell.trainSubview.hidden = YES;
cell.carSubview.hidden = NO;
// configure car cell
}
return cell;
}
the simplest is to make a custom UITableViewCell subclass and create a xib for it. Set the root view in the xib as an uitableviewCell and set its class to your UITableViewCell subclass. Set the file owner class as your TableViewController subclass and add all the subviews you want to it. Then you can simply:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString * CellIdentifier = #"cellIdentifier";
TableViewMessageCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([TableViewMessageCell class])
owner:self
options:nil] lastObject];
}
Message * message = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.message = message;
return cell;
}