Remove subview UIImageview from UIScrollView

stefanosn picture stefanosn · Jan 23, 2010 · Viewed 12k times · Source

Hello i have a uiscrollview and i have one object of uiimageview inside the uiscrollview. I start the app. then i scroll to the right at the scrollview and the scrollview changes but i can not see the next uiimageview object that i add at - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView . before i add the next object i remove the previous...what is wrong?

to remove object i use

UIImageView *l;

    for (NSInteger ko=0; ko<[[scroll subviews] count]; ko++){
        if ([[[scroll subviews] objectAtIndex:0] isKindOfClass:[UIImageView class]]){

            //This code never gets hit
            l=[[scroll subviews] objectAtIndex:0];
            [l removeFromSuperview];
            l=nil;

        }
    }

then i add the next object

[scroll addSubview:imageView];

I remove the previous object because my app crashes when i add 110 images at the scrollview so i have to manage memory i guess. This is why i remove the previous object.

Anyone help please!

Answer

Stefan Arentz picture Stefan Arentz · Jan 23, 2010

First problem I see is that you are looping over an array while also modifying it. Also your ko loop index is not used anywhere. You always grab item 0.

What about:

NSArray* subviews = [[NSArray alloc] initWithArray: scroll.subviews];
for (UIView* view in subviews) {
    if ([view isKindOfClass:[UIImageView class]]) {
         [view removeFromSuperview];
    }
}
[subviews release];

Isn't that exactly what you are trying to do?