xcode从视图中删除某些子视图

xcode从视图中删除某些子视图,xcode,subviews,Xcode,Subviews,大家好, 我是个笨蛋,我已经努力克服这一点好几天了 我正在通过UItouch向视图添加图像。视图包含一个背景,新图像将添加到背景之上。如何清除子视图中添加的图像,而不清除作为背景的UIImage。非常感谢您的帮助。提前谢谢 代码如下: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *) event { NSUInteger numTaps = [[touches anyObject] tapCount]; if (numTa

大家好,

我是个笨蛋,我已经努力克服这一点好几天了

我正在通过UItouch向视图添加图像。视图包含一个背景,新图像将添加到背景之上。如何清除子视图中添加的图像,而不清除作为背景的UIImage。非常感谢您的帮助。提前谢谢

代码如下:

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

if (numTaps==2) {
    imageCounter.text =@"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];

}

}

您需要的是一种将添加的
UIImageView
对象与背景
UIImageView
区分开来的方法。我可以想出两种方法来做到这一点

方法1:为添加的
UIImageView
对象分配一个特殊的标记值

每个
ui视图
对象都有一个
标记
属性,该属性只是一个可用于标识该视图的整数值。可以将每个添加视图的标记值设置为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];
    }
}

仅在一个功能代码行中使用更快速的方法#1代码:

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

答案1通常是正确的,但请注意,您可以使用[UIView viewWithTag:7]限制搜索,而不必遍历每个视图。当然,这可能不会为您节省任何东西,但认识各位是件好事,非常感谢你们的投入。我今天要试试这些。我做了很长一段时间的工作,就是在所有事情都被清除之后,再添加背景。虽然不太优雅,但它确实有效。您的变通方法非常聪明,尽管当您需要对视图进行更多控制时,它可能不太有效。如果您尝试使用@justin建议的
viewWithTag:
,请记住,它只会返回找到的第一个带有匹配标记的视图。当只有一个这样的视图时,这是一种非常方便的方法。如果您有很多带有匹配标记的视图,那么最终您将迭代查找它们。额外提示:视图的默认标记值为零,因此请避免使用零作为标识标记值。这对我来说是一项伟大的工作