Reinhard Männer
Reinhard Männer

Reputation: 15217

Accessory view of a table view cell is only shown in the last cell

I want to display the same accessory view in several table view cells, but it is always shown only in the last row. I thus created a very simple test project, and it behaves the same. Here is the test project:

Header:

#import <UIKit/UIKit.h>
@interface TVController : UITableViewController
@end  

Implementation:

#import "TVController.h"
@interface TVController ()
@property (nonatomic, strong) UIImageView *image;
@end

@implementation TVController
- (void)viewDidLoad{
    [super viewDidLoad];
    self.image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"TestImage38x38"]];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TableViewCell" forIndexPath:indexPath];
    cell.textLabel.text = @"test";
    cell.accessoryView = self.image;
    return cell;
}
@end

Simulator output (the checkmark is the test image):

enter image description here

As you can see, the image is only displayed in the last row, although all cells are set up the same.
What am I doing wrong?

Upvotes: 0

Views: 340

Answers (1)

Szu
Szu

Reputation: 2252

You can't add the same instance of a view to a superview more than once. A view can only have one parent view. You must create instance of UIImageView for each cell:

@property (nonatomic, strong) UIImage *image;
...
self.image = [UIImage imageNamed:@"TestImage38x38"];
...
cell.accessoryView = [[UIImageView alloc] initWithImage:self.image];

Upvotes: 1

Related Questions