2010-04-08 73 views
1

我想要使用自定义的UITableViewCell,并且将它放在与UITableView控制器相同的nib文件中。为此,这些文件是:NTItems.h,NTItems.m和NTItems.xib。自定义单元格只失败

我已经定义在头文件中的单元格:

IBOutlet UITableViewCell *cellview; 

,我已经正确地应用属性:非原子,留住了它的存在:

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

在M文件 - 我已合成可变设备,并使用此来获取定制单元:

- (UITableViewCell *)tableView:(UITableView *)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; 
} 

但是,当我装载表,我得到这个乌七八糟:

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

应该有展示以及数据超过1个细胞。看来只有最后的数据现在正在显示。

+1

如果你可以提供一些更好的上下文代码。 – 2010-04-08 22:25:14

+0

是的,增加了更多:) – bear 2010-04-08 22:40:05

回答

1

您不能从这样的插座重新使用单个单元。考虑一下:每拨号tableView:cellForRowAtIndexPath:,你都会返回同一个单元格。如果可能的话,要求tableView将一个单元出队,并且每次不是时创建一个新单元。

取而代之的是,当您的自定义单元出现故障时,将您的自定义单元存储在单独的笔尖中,并在if (cell == nil) { }代码中读取该笔尖。

包含自定义单元格的nib文件应该有它的文件所有者NSObject,并且它应该只包含单元格的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]; 
    } 

然后在我tableView:cellForRowAtIndexPath:我有:

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

(I使用相同的笔尖的名称作为我的小区重用标识符。)

1

发生了什么事情是,你只在整个表格中使用一个单元格。这意味着最后绘制的单元格是唯一可见的单元格。先前的单元基本上不存在。

您将需要查看此document如何从NIB创建自定义表格视图单元格。

那里有一步一步的指示。