ouahsai
ouahsai

Reputation: 1

UIImageView Disappear after remove image

I tried to remove my images one by one; for that it's ok but when I tried to add a new image by my library nothing appear, I think my code removes my UIImageView.

-(IBAction)remove:(id)sender {

  for (NSUInteger i = 0; i < [self.imageArray count]; i--) {
    UIImageView *view = self.imageArray[i];

    for (view in [self.view.subviews reverseObjectEnumerator])

        if ([view isKindOfClass:[UIImageView class]]){
            [view removeFromSuperview];
            break;

        }

 }

}

Upvotes: 0

Views: 55

Answers (2)

user3821934
user3821934

Reputation:

There are problems with the code you are showing. I am not sure why you have two for loops, and self.imageArray[i] is not even valid Objective-C.

So I am going to assume that you have a view (self.view) which contains subviews, some of which are UIImageViews, and that these are the views you wish to remove.

I would do it like this:

NSMutableArray* viewsToDelete = [NSMutableArray new]; 
for(UIView* view in self.view.subViews) { 
    if([view isKindOfClass:[UIImageView class]){ 
        [viewsTodDelete addObject:view]; 
    } 
} 
// Now remove these 
for(UIImageView* imageView in viewsToDelete){
    [imageView removeFromSuperView]; 
}

Note that [subview removeFromSuperview] will delete the subview from its parents subviews array, and that is a potential source of problems.

I am not sure if my code will solve your original problem, but this code is cleaner and simpler than the code you showed us, so it is a good place to start.

Upvotes: 0

Michael
Michael

Reputation: 6899

If you are simply trying to remove and add UIImageViews from a mutable array, you can use the following the code.

//Create and add items to mutable array
NSMutableArray *arr = [@[] mutableCopy];
[arr addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage1"]]];
[arr addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage2"]]];
[arr addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage3"]]];

//Create temp array to to hold items to remove
NSMutableArray *arrWithItemsToRemove = [@[] mutableCopy];

for(UIView *view in arr)
    if([view isKindOfClass:[UIImageView class]])
        [arrWithItemsToRemove addObject:view];

//Remove objects
[arr removeObjectsInArray:arrWithItemsToRemove];

NSLog(@"%@", arr);

Upvotes: 1

Related Questions