我正在尝试使用以下代码在我的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上随机重新显示(btw只有1个部分),滚动变得非常生涩和滞后......我向上/向下滚动的越多,它的实例就越多! 为什么?这里的错误在哪里?
帮助,谢谢!
答案 0 :(得分:21)
细胞被重复使用。您需要每次都重置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;
}
答案 1 :(得分:0)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell;
if(indexPath.row == 5 || indexPath.row == 9) {
cell = [tableView dequeueReusableCellWithIdentifier:@"TopicCellWithImage"];
} else {
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;
}
答案 2 :(得分:0)
要在 Swift 4和Swift 5
中显示自定义的AccessoriesView单元格let lockIcon = UIImage(named: "lock_icon")
let lockIconView = UIImageView(image: lockIcon)
lockIconView.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
cell.accessoryView = lockIconView