开发者

Custom cell just failing

I'm trying to use a custom UITableViewCell, and I've placed it in the same nib file as the UITableView controller. For this, the files are: NTItems.h, NTItems.m and NTItems.xib.

I have defined the cell in the header file:

IBOutlet UITableViewCell *cellview;

and I've correctly applied the property: nonatomic, retain so it's there:

@property (nonatomic, retain) IBOutlet UITableViewCell *cellview;

In the m file - I've synthesized the variable device and am using this to get the custom cell:

- (UITableViewCell *)tableView:(UITa开发者_如何学编程bleView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   static NSString *CellIdentifier = @"cellview";

   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

   if (cell == nil) {
    cell = self.cellview;
   }

   Product *aProduct = [appDelegate.products objectAtIndex:indexPath.row];

   name.text  = aProduct.name;
   upc.text   = [NSString stringWithFormat:@"UPC%@",aProduct.upc];
   price.text = aProduct.pid;
   return cell;
 }

However, when I load the table, I get this horrible mess:

alt text http://dl.dropbox.com/u/1545603/tablecellissue.png

There should be more than 1 cell showing data as well. It appears that only the last data is showing up right now.


You can't reuse a single cell from an outlet like this. Think about it: you're returning the same cell for every call to tableView:cellForRowAtIndexPath:. It's your job to ask the tableView to dequeue a cell if possible, and create a new one each time it isn't.

Instead, store your custom cell in a separate nib and read that nib within your if (cell == nil) { } code when dequeue fails.

The nib file that contains the custom cell should have its File's Owner NSObject and it should contain only the cell's nib (no other objects).

I use this function to load the nib:

- (id)loadObjectFromNibNamed: (NSString *)inName;
{
    id objectsInNib = [[NSBundle mainBundle] loadNibNamed: inName
                                                     owner: self
                                                   options: nil];
     NSAssert1( objectsInNib != nil, @"loadNibNamed %@ returned nil", inName );
     NSAssert2( [objectsInNib count] == 1, @"lodNibNamed %@ returned %d items", inName, [objectsInNib count] );
     return [objectsInNib objectAtIndex: 0];
    }

Then in my tableView:cellForRowAtIndexPath: I have:

if ( cell == nil ) {
    cell = [self loadObjectFromNibNamed: nibName];
}

(I use the same nib name as my cell reuse identifier.)


What's happening is that you're only using one cell for the entire table. That means that the last cell drawn is the only visible one. The prior cells essentially don't exist.

You will want to review this document on how to create custom table view cells from a NIB.

There are step by step instructions there.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜