Reputation: 2930
I have a tableview and I want to add an imageview to the contentView of the cell at the row it was selected in.
This is my current code and when I click any cell it only adds the imageView to the last row rather than the row I click on.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
playIcon = [[UIImageView alloc]initWithFrame:CGRectMake(20, 22, 9, 12)];
UIImage *image = [UIImage imageNamed: @"cell_play.png"];
[playIcon setImage:image];
[cell.contentView addSubview:playIcon];
}
Upvotes: 1
Views: 1821
Reputation: 1771
work for me with UIcollectionView and UItableviewcell in Swift 2.0:
CV_Posts.cellForItemAtIndexPath(index)?.addSubview(imag_curtir)
Upvotes: 0
Reputation: 12641
You can do like this
[[tableView cellForRowAtIndexPath:indexPath] addSubview:playIcon];
Upvotes: 1
Reputation: 5960
First, you have not identified a cell at a particular row. Since your compiler didn't complain, I assume that cell is an ivar. It is pointing to the last cell that it was pointed to, which very well may be the last cell in the table.
You have to be careful that you don't set the content of a cell outside of the UITableview methods, including the UITableView method cellForRowAtIndexPath:`. This is described in a recent answer I provided at this link.
So if you looked at that answer, you will have read that the tableview methods make sure the cell is rendered correctly even when the tableview scrolls and cells appear and disappear. I recommend that you set up your data source with some kind of tag or property that you can use to see that this image needs to be present. That way, it will be there even if you scroll the cell so it dissappears and reappears.
Upvotes: 0