UITableView cell accessoryView image issue
The cells get reused. You need to reset the accessoryView each time. Its just a small change:
- (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;
}
Just for completion, you can also use Eric's solution like this - it may be faster, since the imageView is not created every time. But thats only a minimal difference. Probably your lags have other reasons.
- (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;
}
To showing custom accessoryView cell in Swift 4 & Swift 5
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