Reputation: 1118
I am having some issues with adding some images within custom cells within my table. A UIView
is created in each cell, which is then assigned a unique tag. I have been testing by trying to add an image to one specific cell, say using tag "2204" for example, but it will still add that image to every 3rd cell (2201, 2204, and so on...), so I am unsure of what could even cause that. I setup a label in each cell to display the current tag of the view, and it shows that the tags are correct, but why then would it place the images in the other cells?
I have only one section in this table, and it is only going by rows. By default, 5 rows show, but more rows can be added.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
workoutTableViewCell *cell = (workoutTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[workoutTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.exerciseViewArea.tag = 2200 + indexPath.row;
//using fifth cell as a test
testview = [self.view viewWithTag:2204];
return cell;
}
- (void)changeExerciseImage
{
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(9,10,20,20)];
imageView.image = [UIImage imageNamed:@"testImage.png"];
[testview addSubview:imageView];
[testview bringSubviewToFront:imageView];
NSLog(@"changed exercise image to %@", _exerciseTempText);
}
Upvotes: 0
Views: 669
Reputation: 16124
Cells can get reused by the UITableView
so rather than keeping a reference to an individual cell you are better off updating the data source and then calling reloadData
or reloadItemsAtIndexPaths
. So for example you could have a NSMutableArray
of image names to use for each cell and then do something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
workoutTableViewCell *cell = (workoutTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[workoutTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(9,10,20,20)];
[imageView setTag:myImageViewTag];
[cell.exerciseViewArea addSubview:imageView];
[cell.exerciseViewArea bringSubviewToFront:imageView];
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
UIImageView *imageView = (UIImageView *)[cell.exerciseViewArea viewWithTag:myImageViewTag];
[imageView setImage:[UIImage imageNamed:[myArrayImages objectAtIndex:indexPath.row]]];
}
- (void)changeExerciseImage
{
[myArrayImages replaceObjectAtIndex:4 withObject:@"testImage.png"];
[myTableView reloadData]; //or just update that cell with reloadItemsAtIndexPaths
}
Upvotes: 1