2011-09-09 99 views
3

在我的TableVIew Im加載Custome單元格與Xib,爲CellForIndexPath的每個項目,重新創建單元格。如何避免細胞的娛樂?表格單元格娛樂當單元格加載時與xib

Iam新的iPhone,請幫助我。

+0

Post your cellForRowAtIndexPath method may be?因此,我們將能夠發現錯誤... – Vladimir

+0

發佈代碼將有所幫助! – mayuur

回答

1

當您從Nib加載視圖時,每次調用cellForRowAtIndexPath時都會分配內存,因此每次只更新一次單元而不是alloc內存是更好的方法。 可能下面的例子會幫助你。

參數化在自定義單元格中的標籤。像

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { 
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) { 
lblusername=[[UILabel alloc]initWithFrame:CGRectMake(70, 10, 150, 25)]; 
    lblusername.backgroundColor=[UIColor clearColor]; 
    lblusername.textColor=[UIColor colorWithRed:33.0/255.0 green:82.0/255.0 blue:87.0/255.0 alpha:1.0]; 
    [contentview addSubview:lblusername]; 
    [lblusername release]; 
} 
return self; 
} 

並使用下面列出的代碼調用自定義單元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

static NSString *CellIdentifier = @"Cell"; 

LeaderboardCustomeCell *cell = (LeaderboardCustomeCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[LeaderboardCustomeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
} 
[email protected]"Hello"; 
} 
4

您可以使用標準方法來緩存先前創建的單元格。在你- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath方法,你應該創建一個使用下一個方法細胞:

static NSString *CellIdentifier = @"YourCellIdentifier"; 
cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    // create (alloc + init) new one 
    [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];   
    cell = myCell; 
    self.myCell = nil; 
} 
// using new cell or previously created 

不要忘了,你會在內存中的對象存儲所有可見單元格。當你滾動你的表格時,這些單元格將被重新使用。例如,如果你有10個可見的單元格,那麼單元格將會== 10次,你會分配+ init init。當您向下滾動時,會創建一個更多的單元格(因爲將會顯示11個單元格),對於12個單元格,您將重新使用爲第一個單元格創建的單元格。

正如@rckoenes所說,不要忘記在IB中設置相同的CellIdentifier

希望,我很清楚。

+2

最重要的是在「接口」構建器中設置單元的cellIdentifier。 – rckoenes

+0

謝謝,更新了我的答案 – Nekto