简体   繁体   中英

Remove subview UIImageview from UIScrollView

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!

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?

A couple of suggestions to get you on the right track:

  1. If you believe that memory is an issue, partition up the problem. For example add/remove 10 images at a time.

  2. The tag property of a UIView is your best friend when trying to avoid maintaining problems with your own loops. You can set a specific tag for your UIImageViews when you need them, and then search for the tag using [UIView viewWithTag:tag]; It works recursively.

  3. st3fan brings up a very good point about concurrent modification. In general a good way to avoid it is to add to a "deletion array" and then removeObjectsInArray.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM