我正在尝试使用以下代码在我的 UITableViewCells 的特定行上显示“挂锁”图标:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCell"];
GPBTopic *topic = [self.topics.list objectAtIndex:indexPath.row];
cell.textLabel.text= topic.name;
if ((indexPath.row == 5) || (indexPath.row == 9))
{
cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:@"lock_icon.png"]];;
[cell.accessoryView setFrame:CGRectMake(0, 0, 24, 24)];
}
return cell;
}
我得到了一个有趣的结果 - 挂锁最初显示在第 5,9 行,但是当我向下和向上滚动列表时,图标也会随机重新显示在其他单元格的 accessoryView 上(顺便说一句,只有 1 个部分),并且滚动变得非常不稳定和滞后......我向上/向下滚动的次数越多,显示的实例就越多! 为什么?这里的错误在哪里?
帮忙,谢谢!
最佳答案
细胞得到重用。您需要每次重置 accessoryView。 这只是一个小改动:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCell"];
GPBTopic *topic = [self.topics.list objectAtIndex:indexPath.row];
cell.textLabel.text= topic.name;
if ((indexPath.row == 5) || (indexPath.row == 9))
{
cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:@"lock_icon.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 24, 24)];
} else {
cell.accessoryView = nil;
}
return cell;
}
为了完成,您也可以像这样使用 Eric 的解决方案 - 它可能会更快,因为 imageView 并不是每次都创建。但这只是很小的区别。可能您的滞后有其他原因。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
if(indexPath.row == 5 || indexPath.row == 9) {
cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCellWithImage"];
cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:@"lock_icon.png"]];;
[cell.accessoryView setFrame:CGRectMake(0, 0, 24, 24)];
} else {
cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCell"];
}
GPBTopic *topic = [self.topics.list objectAtIndex:indexPath.row];
cell.textLabel.text= topic.name;
return cell;
}
关于ios - UITableView cell accessoryView 图片问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15349983/