我知道这已经被广泛讨论过,而且我敢肯定,我只是简单地遗漏了一些东西,但是像我之前的许多其他人一样,我在 UITableView 中重用单元格时遇到了问题......我有一个按钮显示头像,我第一次异步下载它,然后缓存它以供以后使用......当我在第一次下载图像时滚动我的表格视图时,头像错误地出现在被重用的单元格中,尽管我'在开始下载之前将头像设置为默认头像,所以我希望这里有人知道解决方案...
在 cellForRowAtIndexPath 中:
WaitingCell *waitingCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifierWaiting];
if (waitingCell == nil) {
waitingCell = [[WaitingCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifierWaiting];
waitingCell.delegate = self;
}
[waitingCell.userButton setImage:[UIImage imageNamed:DefaultAvatar] forState:UIControlStateNormal];
[waitingCell.usernameLabel setText:username];
[waitingCell.scoreLabel setText:score];
__block UIImage *img;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
if([p1.objectId isEqualToString:currentUser.objectId])
{
img = [profileImages getProfileImageForUser:[p2 objectId]];
waitingCell.user = p2;
} else
{
img = [profileImages getProfileImageForUser:[p1 objectId]];
waitingCell.user = p1;
}
dispatch_async(dispatch_get_main_queue(), ^{
[waitingCell.userButton setImage:img forState:UIControlStateNormal];
});
return waitingCell;
“userButton”的图像是在图像完全缓存之前被重用的部分,但我认为通过将其设置为默认值(DefaultAvatar 是一个常量文件名),它会简单地设置默认头像,直到另一个被下载因此它不会重用其他图像..
该按钮在我的名为 WaitingCell 的自定义 UITableViewCell 中定义,如下所示:
self.userButton = [UIButton buttonWithType:UIButtonTypeCustom];
[self.userButton setImage:[UIImage imageNamed:PlaceholderAvatar] forState:UIControlStateNormal];
self.userButton.frame = CGRectMake(20, 8, 51, 54);
[self.contentView addSubview:self.userButton];
有什么想法可以防止它重复使用图像并简单地使用 DefaultAvatar 直到下载正确的图像?