简体   繁体   中英

Remove all instances from superview

I'm trying to remove all Sprites (UIImageViews) on my screen with the following code:

-(IBAction)clearAll:(id)sender{
      for (Sprite *sprite in self.view.subviews){
      [sprite removeFromSuperview];
}

However, when this code runs, elements from my Storyboard which are NOT Sprites are removed. Actually, everything in the view is pretty much removed.

What is going on?

This isn't how for in loops work. Just because you've specified a type, doesn't mean that only objects of that type will be affected. Every view in subviews responds to removeFromSuperview , so regardless of what it has been cast as, it'll still be removed.

If you want to remove only Sprite objects, then you need to check the class of each object.

for (UIView *view in self.view.subviews)
{
    if ([view isKindOfClass:[Sprite class]])
        [view removeFromSuperview];
}

We can remove all the instances of UIView types from its SuperView using following statement.

[[self.view subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

It looks cleaner,simpler rather than doing a loop.

In this case, subviews contains everything (sprites and other objects). Your enumeration does not only return sprites - it returns everything (but loosely 'casts' them as sprites). In this case, everything that is a subview responds to the removeFromSuperview method - so everything gets removed.

You need to check for the type of the object as you loop through the subviews to determine if it needs to be removed.

Your code is calling removeFromSuperview on all subviews of self.view, and is therefore working correctly as it is written. The reason this code runs is because Sprite is probably a subclass of UIView, so the compiler doesn't error/warn you. What you need to do is more like this:

-(IBAction)clearAll:(id)sender{
    for (UIView *aSubview in self.view.subviews){
    if ([aSubview isSubclassOf
    [sprite removeFromSuperview];
}

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