自定义UITableViewCell消失

时间:2010-01-12 15:31:13

标签: iphone uitableview

我见过很多人都有类似的问题,但要么他们的解决方案没有帮助,要么就是太不同了。

我的问题是,我有自定义的UITableViewCell,自定义大小,图像和内容。当我向上或向下滚动然后再向后滚动时,某些单元格中的文本会消失。这似乎是随机发生的。

我已经阅读了关于“出队”的问题,但要么我弄错了,要么就是我的情况......

无论如何,继承了我的Cell的代码:

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

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:CellIdentifier] autorelease];
}

cell.selectionStyle = UITableViewCellSelectionStyleNone;


cell.imageView.image = [[UIImage alloc] initWithContentsOfFile:
                        [[NSBundle mainBundle]  pathForResource:
                         [[shopItems  objectAtIndex:indexPath.row] name] ofType:@"jpg"]];

UITextField *temp= [[UITextField alloc] initWithFrame:cell.frame];
temp.text = [[shopItems objectAtIndex:indexPath.row] name];
temp.textColor = [UIColor whiteColor];
temp.textAlignment = UITextAlignmentCenter; 


UIImageView *cellView = [[UIImageView alloc] initWithImage:[[UIImage alloc] initWithContentsOfFile:
                                                                   [[NSBundle mainBundle] pathForResource:@"smalltabs_wide_bg"  ofType:@"png"]]];

[cellView addSubview:temp];

cell.backgroundView = cellView;



return cell;
}

你对此有什么想法吗?

4 个答案:

答案 0 :(得分:2)

可能的问题是每次(重新)使用单元格时都会向单元格添加UITextField和UIImageView。您的代码应该是

 {
   ...
   if (cell == nil) {
       cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:CellIdentifier] autorelease];

   // Insert all subviews to cell here
   }

   // setup cell's subviews here
   ...
   }

还要记住代码中的所有内存泄漏 - 当您使用alloc创建内容时,必须将其释放到某处。

答案 1 :(得分:1)

答案 2 :(得分:0)

一个问题是你没有释放你的临时UITextField,这会导致内存泄漏,并可能导致问题。

答案 3 :(得分:0)

分享我的经验:

有类似的问题。我在应用程序中有很多表,其中一个数据会随机消失,最终整个表都会消失。

对我而言,问题在于我将细胞出列,给予他们所有相同的“独特”身份。因此,几个表共享相同的ID,我相信它们是相互冲突的,并且弄乱了我正在查看的单元格。

给每张桌子它自己的唯一标识符为我解决了问题。 (DAH!)

(也在这里发布,可能是重复的:UITableView custom cell images disappear after scrolling.