2010-11-09 139 views
11

全部问候,xcode从视图中删除一些子视图

我是一个noob,我一直试图通过这几天工作。

我正在通过UItouch将图像添加到视图。该视图包含添加新图像的背景。如何清除我从子视图中添加的图像,而无需摆脱作为背景的UIImage。任何援助非常感谢。提前致谢。

这里是代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event { 
NSUInteger numTaps = [[touches anyObject] tapCount]; 

if (numTaps==2) { 
    imageCounter.text [email protected]"two taps registered";  

//__ remove images 
    UIView* subview; 
    while ((subview = [[self.view subviews] lastObject]) != nil) 
     [subview removeFromSuperview]; 

    return; 

}else { 

    UITouch *touch = [touches anyObject]; 
    CGPoint touchPoint = [touch locationInView:self.view]; 
    CGRect myImageRect = CGRectMake((touchPoint.x -40), (touchPoint.y -45), 80.0f, 90.0f); 
    UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect]; 

    [myImage setImage:[UIImage imageNamed:@"pg6_dog_button.png"]]; 
    myImage.opaque = YES; // explicitly opaque for performance 


    [self.view addSubview:myImage]; 
    [myImage release]; 

    [imagesArray addObject:myImage]; 

    NSNumber *arrayCount =[self.view.subviews count]; 
    viewArrayCount.text =[NSString stringWithFormat:@"%d",arrayCount]; 
    imageCount=imageCount++; 
    imageCounter.text =[NSString stringWithFormat:@"%d",imageCount]; 

} 

}

回答

28

你需要的是从背景UIImageView区分添加UIImageView对象的方式。有两种方法我可以考虑这样做。

方法1:分配加入UIImageView对象特殊的标记值

每个UIView对象具有属性tag其仅仅是可以用于识别该视图的整数值。可以在每次添加的视图的标签值设置为7这样的:

myImage.tag = 7; 

然后,除去增加的视图,您可以通过所有的子视图的步骤,只用7%的标记值删除的:

for (UIView *subview in [self.view subviews]) { 
    if (subview.tag == 7) { 
     [subview removeFromSuperview]; 
    } 
} 

方法2:记住背景视图

另一种方法是保持到后台视图的引用,所以你可以从增加的视图区分开来。为背景UIImageView制作一个IBOutlet,并在Interface Builder中以通常的方式分配它。然后,在删除子视图之前,确保它不是背景视图。

for (UIView *subview in [self.view subviews]) { 
    if (subview != self.backgroundImageView) { 
     [subview removeFromSuperview]; 
    } 
} 
+2

回答1通常是正确的,但请注意,您可以使用限制搜索[UIView的viewWithTag:7]不必遍历每一个视图。当然,这可能无法为你节省任何东西,但知道 – justin 2010-11-09 22:29:49

+0

是一件很棒的事情,你们都非常感谢你的意见。我今天会试一试。我做了很长时间的工作,其中的一切都是在所有事情都被清除后重新添加背景。不完全优雅,但它的工作.. – 2010-11-10 17:24:26

+1

你的解决方法是非常聪明,但它可能无法很好地工作,当你需要更多的控制你的意见。如果您按照@justin的建议尝试使用'viewWithTag:',请记住它只会返回匹配标签找到的第一个视图。只有一个这样的视图时,这是一个非常方便的方法。如果你有很多匹配标签的视图,你最终会迭代找到它们。额外提示:视图的默认标记值为零,因此请避免使用零作为标识标记值。 – 2010-11-10 18:05:19

0

只有一个代码功能线的方法#1更迅速代码:

self.view.subviews.filter({$0.tag == 7}).forEach({$0.removeFromSuperview()})