views:

50

answers:

2

I need to close a series of views and don't wont to write code for closing them one by one. Here's a sample code to illustrate what I mean:

//This is the method for placing the views. It's called at different times at runtime:

- (void)addNotePic:(int)number {

int indexNumber = ((110*number) + 10);

UIImage *image = [UIImage imageNamed:@"Note.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
[image release];
imageView.frame = CGRectMake(10, indexNumber, 300, 100);
imageView.tag = 100 + number;
[self.view addSubview: imageView];
[self.view sendSubviewToBack: imageView];
[imageView release];

}

//And heres the issue-part, and the thing I'm asking you guys about. This is the method that I wish to remove all the displayed views at once.

    for (i = 0; i < 20; i++) {
    UIView *imageView = [self.view viewWithTag:100 + i];
    [imageView removeFromSuperview];
}

I know this results in errors, since I try to redefine imageView the second time it loops, but how can I work around this. Might be something to rename the name 'imageView' to 'imageView + i' or something more clever. Would love a good suggestion...

A: 

I admit I am taking a quick guess, but would this work?

    for (i = 0; i < 20; i++) {
    [[self.view viewWithTag:100 + i] removeFromSuperview];
}
dredful
Think I tried that last night, but it didn't seem to target the views correctly. I'll try again when I come home...
John Kofod
A: 

The following will remove all UIImageViews from self.view. Note that the mutable array is necessary as you cannot modify an array that is being iterated over ( as in the for loop)

NSMutableArray *removeThese = [NSMutableArray arrayWithCapacity:5];

for (UIView *view in self.view.subviews) {
 if([view isKindOfClass:[UIImageView class]]) {
  // [view removeFromSuperview]; <-- This will result in a runtime error
  [removeThese addObject:view];
 }
}

[removeThese makeObjectsPerformSelector:@selector(removeFromSuperview)];
TomH
I'll try it when I get home...
John Kofod