2011-07-24 210 views
1

我创建了一个自定义的UITableViewCell,但在更新单元格内容时遇到了问题。当我在表格中有多个单元格时,表格未在单元格中绘制正确的图像。每个单元格中的图像应该是唯一的,但是我看到不同的单元格具有相同的图像。该表似乎是随机放置细胞。UITableViewCell没有正确更新

我用NSLog检查了我的数据源,名称正确。当我不使用- (UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier时,我可以更正此问题,但每次在- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath时都会创建一个新单元。

任何关于我可能做错的建议?请看下面我的代码。

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    ScoreCell *cell = (ScoreCell *)[_tableView dequeueReusableCellWithIdentifier:@"CellID"]; 

    if (cell == nil) 
    { 
     cell = [[[ScoreCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellID"] autorelease]; 
    } 

    BoxScore *boxScore = [_gameDayData objectAtIndex:indexPath.row]; 
    [cell setScoreImage:[UIImage imageNamed:boxScore.name]]; 

    return cell; 
} 

ScoreCell.h

@interface ScoreCell : UITableViewCell 
{ 
    UIImage *scoreImage; 
} 

@property(nonatomic, retain)UIImage *scoreImage; 

@end 

ScoreCell.m

@implementation ScoreCell 

@synthesize scoreImage; 

- (void)dealloc 
{ 
    [scoreImage release], scoreImage = nil; 
} 


- (void)drawRect:(CGRect)rect 
{ 
    [super drawRect:rect]; 

    [scoreImage drawAtPoint:CGPointMake(5,5)]; 
} 

@end 
+0

这个类名不要jive - 我希望这是在这里发布snippits的神器 – bshirley

+0

谢谢,这是一个神器。固定。 – David

+0

表面随机性不可能是随机的 - 当一个单元格滚动出视图时,它会被重用。一个是从另一侧滚动,如果状态没有被你的代码正确重置,你会得到你看到的行为 – bshirley

回答

3

图像处理有两个与图像处理无关的问题。 滚动关闭并在屏幕上将导致一个单元格加载图像两次(或一百次,取决于用户)。

你想要一个

- (UIImage *)boxScoreImageForIndex:(NSInteger)index 

方法(懒惰)负载,扶住,并为细胞的图像。

你也不想使用imageNamed:,在你的情况下,它会导致内存使用量超过需要的两倍。改为使用imageWithContentsOfFile:

+0

出于某种原因,'imageWithContentsOfFile:'工作并且'imageNamed:'没有。我还添加了'[cell setNeedsDisplay]'。谢谢。 – David

0

您还没有清除之前的图像。当一个单元出队时,它不被处理。

因此,有时在单元格上绘制的图像会在新图像前显示。

在drawRect中,您需要清除所有内容。

要么是:

CGContextClearRect(context , [self bounds]); 
对细胞

或者设置clearsContextBeforeDrawing创建时。

+0

'clearsContextBeforeDrawing'默认设置为yes。我不太确定'CGContextClearRect'。 – David

5

除了其他意见,请务必在您的ScoreCell类中实施-prepareForReuse方法。当细胞被重新使用时,它会被调用,此时应该清除图像。请务必在实施中致电[super prepareForReuse];。这将防止细胞被错误的图像重复使用。

+1

感谢您的提示。我认为'prepareForReuse'是放置'setNeedsDisplay'好得多的地方,它强制单元重绘它的内容。 – David