I have a MasterViewController displaying Items. Selecting an Item (ItemA), displays images of ItemA in a DetailViewController. The DeatilViewController contains a scrollView, displaying all the images.
When tableView:didSelectRowAtIndexPath is called, the images is added to an UIImageView, that is tagged and added as a subview to a scrollview.
NSUInteger i;
for (i = 1; i <= numberOfImages; i++)
{
NSString *imageName = [ItemAImages objectAtIndex:i-1];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.tag = i;
[scrollView addSubview:imageView];
}
Works fine. But when I go back to the MasterViewController, and selects a ItemB, the ItemA is still displayed, like the iPhone simulator refuses to forget the previous scrollview,containing ItemA images. I have tried
for(UIView *subview in [scrollView subviews])
{
[subview removeFromSuperview];
}
which results in either no scrollview at all, or no effect. Depending on when this method is called.
How can I “reset” the scrollview for the next Item?
You have to remove every subview of your scrollview.
So you have to call
removeFromSuperviewnot on thescrollViewitself but on each and every of its subviews.Be careful when you do that as your array of subviews (returned by
scrollview.subviews) is going to change while you iterate thru it and remove the subviews. So better make a copy of this list of subviews and iterate on that copy:Note: Always avoid to modify the collection over which you are iterating. Also because you will risk to skip some objects in your enumeration. For exemple if you have an array
@[A,B,C,D,E]and iterate over the content to remove the objects, your code will probably say “remove the object at index 0, then the object at index 1, then the one at index 2…. But once you have remove the object at index 0, the collection would have changed to@[B,C,D,E]and the array at index 1 would be C, not B which you would then have skipped. And once you removed object at index 1, your collection will have become@[B,D,E]and removing object at index 2 next will result in@[B,D]…I don’t know if that’s the cause of your problem, that makes you miss some subviews, but if you did it that way it probably explains why it didn’t work properly.