开发者

Close a series of views in a for-loop [iPhone]

I nee开发者_StackOverflowd 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...


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

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


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)];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜