2011-11-22 76 views
0

我有这样的代码:IOS:删除ImageView的

for(Contact *contact in myArray){ 
     if(...){ 
      UIImageView *fix = [[UIImageView alloc] initWithImage:myImage]; 
      [self.view addSubview:fix]; 
      [fix setFrame:[contact square]]; 
      return; 
     } 
    } 

在这段代码我在self.view添加ImageView的,但在我的应用我把这个“为”很多次,终于我有我的self.view与4或5 imageView“修复”。 从self.view中删除所有这些imageView的方法是什么?

+0

return-statement将返回该方法。 – vikingosegundo

回答

3

如果你只是想删除的UIImageView的情况下,你可以尝试这样的事:

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

更新:

由于vikingosegundo在评论中写道: ,你可以做这个instad。

如果你把每imageview的添加到一个数组,你可以从视图以后这样的删除:

NSMutableArray *images = [[NSMutableArray alloc] init]; 

for Contact *contact in myArray){ 
    if(...){ 
     UIImageView *fix = [[UIImageView alloc] initWithImage:myImage]; 
     [self.view addSubview:fix]; 
     [fix setFrame:[contact square]]; 
     [images addObject:fix]; // Add the image to the array. 
     return; 
    } 
} 

的后面,从画面中移除:

for (UIImageView *v in images) { 
    [v removeFromSuperview]; 
} 
+1

以这种方式删除我所有的imageView,但我应该只删除那些添加在我的“for”中的图片;我可以使用NSMutableArray吗? – CrazyDev

+0

您不能直接将UIImageView添加到数组,然后通过从数组中引用它们将其从self.view中移除。你需要对每个UIImageView的引用(即一个标签)。我更新了我的答案,我希望这对你有用。 – matsr

+0

好的,谢谢....... – CrazyDev

1

只需为每个子视图调用removeFromSuperview。喜欢的东西:

for(UIView *subview in self.view.subviews) 
    [subview removeFromSuperview]; 
1
NSMutableArray *images = [NSMutableArray array]; 

for Contact *contact in myArray){ 
    if(...){ 
     UIImageView *fix = [[UIImageView alloc] initWithImage:myImage]; 
     [self.view addSubview:fix]; 
     [fix setFrame:[contact square]]; 
     [images addObject:fix]; 
    } 
} 


for (UIView *v in images){ 
    [v removeFromSuperview]; 
} 

另一种方法

for(UIView *v in self.view.subviews) 
    if([v isKindOfClass:[UIImageView class]]) 
     [v removeFromSuperview]; 

我把example放在一起。