2010-04-08 77 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創建自定義表格視圖單元格。

那裏有一步一步的指示。