2015-01-06 77 views
0

我正在使用循環向視圖添加多個視圖。如何從ios中包含多個子視圖的超級視圖中刪除特定的子視圖

float contactsContainerX = 6.0f; 

UIView *contactsContainer=[[UIView alloc] initWithFrame:CGRectMake(0.0f,4.0f,110.0f,22.0f)]; 
      contactsContainer.backgroundColor=[UIColor colorWithRed:213.0f/255.0f green:213.0f/255.0f blue:213.0f/255.0f alpha:1.0f]; 

UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(90.0f, 2.0f, 18.0f, 18.0f)]; 
closeButton.backgroundColor = [UIColor yellowColor]; 

[closeButton addTarget:self action:@selector(removeFavouriteContact:) forControlEvents:UIControlEventTouchUpInside]; 
[contactsContainer addSubview:closeButton]; 

for(int x=0; x<3;x++) 
{ 
    contactsContainer.frame = CGRectMake(contactsContainerX, contactsContainer.frame.origin.y, contactsContainer.frame.size.width, contactsContainer.frame.size.height); 
    [self.contactsViewSuperContainers addSubview:contactsContainer]; 
    contactsContainerX = contactsContainer.frame.origin.x + contactsContainer.frame.size.width+6.0f; 
    self.contactsScroller.contentSize =CGSizeMake(contactsContainerX,self.contactsViewSuperContainers.frame.size.height); 
} 

現在,只要我點擊按鈕。該行動應該刪除我點擊的特定子視圖。我的意思是代碼是什麼?請幫幫我。

-(void) removeFavouriteContact: (UIButton *) sender 
{ 

    for(UIView *subview in self.contactsScroller.subviews) 
     if (self.contactsScroller.subviews) 
     { 
      //<#statements#> 
      //[self.view removeFromSuperview]; 

     } 

} 
+1

[[sender superview] removeFromSuperview]; – Astoria

+0

您的第一個代碼塊看起來不正確。在你的循環內,你每次都添加相同的視圖。視圖只能添加到另一個視圖一次。 – rmaddy

回答

1

考慮您的Button直接添加到您的循環添加的View,你可以很容易地通過使用

-(void) removeFavouriteContact :(id)sender { 
    [[sender superview] removeFromSuperView]; 
} 

訪問你的行動SuperView如果你的按鈕上面的代碼將只工作直接添加到視圖中,如果沒有檢查它所添加的按鈕的級別,在深層次上,您可以追加superview並獲得如下的精確超級視圖

[[[[sender superview] superview] superview] removeFromSuperView]; 

希望它有幫助。

乾杯。

+0

它工作,感謝很多! – Poles

-1

僅使用一個線

[[someUIView子視圖] makeObjectsPerformSelector:@selector(removeFromSuperview)];

+2

這將刪除所有子視圖。 OP只是想刪除一個子視圖。 – rmaddy

0

使用tagviewWithTag屬性。設置爲tag爲您的view & button並使用tag獲得該view然後將其刪除。

-(void) removeFavouriteContact :(id)sender { 
    NSInteger tag = sender.tag; 
    UIView *view = [contactsContainer viewWithTag:tag]; 
    [view removeFromSuperView]; 
} 
+0

由於我使用相同的UIView生成多個視圖,如果我爲每個UIView設置標記,循環的最後一個值是作爲最終標記值存儲。所以每當我點擊任何子視圖按鈕'2'被記錄。 – Poles

+0

@rmaddy,已經提到你做錯了。你應該只添加一次你的視圖。 – arthankamal