removeFromSuperview UIImageView not working

2019-07-25 08:37发布

问题:

I am trying to remove an image from an existing view using the code below:

-(void) deleteImage:(int)imageID{

//[self.imageArray removeObjectAtIndex:imageID];
//remove the image from the screen
for (UIView* view in self.view.subviews) {
    if ([view isKindOfClass:[UIImageView class]] && [view tag] == imageID) {
        //could be a bug here with the re-Ordering of the array (could add a helper method to reset all the tags on screen when this is called
        NSLog(@"view %@", view);
        //[self.imageArray removeObjectAtIndex:imageID];
        [view removeFromSuperview];
    }
  }
}

The NSLog outputs the following:

view <UIImageView: 0x18b8d7b0; frame = (0 0; 768 2016); autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x18b8d890>>

The issue i have is that it appears to be getting the ImageView but it doesn't remove it.

回答1:

Since you're trying to modify the user interface, you must be doing it on the Main thread. Therefore, do the following:

dispatch_async(dispatch_get_main_queue(), ^{
    [view removeFromSuperview];
});


回答2:

First of all, when you ask a view for its subviews, you get a copy of the subviews array, so fiddling with the copy array doesn't do you any good.

Secondly, in principle, you should be getting a crash when you try to remove the subview, because you are using fast enumeration, which prohibits mutating the collection while in the enumeration.

Lastly, the correct method of removing a subview of a view is to use the removeFromSuperview method, which implies that you do need to keep a reference to the image view in question.

Essentially, you should use the methods provided in the UIView section titled 'Managing the View Hierarchy', and not to be grubbing around with the actual subview arrays themselves. That's a recipe for potentially getting the subviews hierarchy into an inconsistent state.