2010-11-09 105 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()})