2012-06-27 67 views
0

在其中一個iPad應用程序中,我正在工作我已將自定義視圖添加到視圖。此工作正常,但現在我想要刪除所有添加的自定義視圖。如何執行此操作?如何刪除以編程方式添加的customviews?

以下是我添加自定義視圖

for (int col=0; col<colsInRow; col++) { 
     // NSLog(@"Column Number is%d",col); 
     x=gapMargin+col*width+gapH*col; 


     //self.styleButton=[[UIButton alloc] initWithFrame:CGRectMake(x, y, width, height)]; 
     ComponentCustomView *componentCustomobject=[[ComponentCustomView alloc] initWithFrame:CGRectMake(x, y, width, height)]; 
     componentCustomobject.backgroundColor=[UIColor redColor]; 
     componentCustomobject.componentLabel.text=[appDelegate.componentsArray objectAtIndex:row]; 
     [self.formConatinerView addSubview:componentCustomobject]; 
     tempCount1++; 
    } 

回答

4

您可以從父視圖中除去類型ComponentCustomView的所有子視圖代碼

for (UIView *view in self.formConatinerView.subviews) { 
    if ([view isKindOfClass:[ComponentCustomView class]) { 
     [view removeFromSuperview]; 
    } 
} 
0
NSArray *arr = [self.view subViews]; 

for (UIView *view in arr) { 
    if ([view isKindOfClass:[ComponentCustomView class]) { 
     [view removeFromSuperview]; 
    } 
} 
0

我不知道,如果刪除對象(在這種情況下,subviews)安全或不安全(我記得閱讀了有關Mac OS X和iOS之間的差異,但不知道...);除非屬性subviews返回內部陣列的副本(很可能因爲內部陣列需要可變),所以100%安全,即時的方式可以做到這一點:

NSArray* copyOfSubviews = [[NSMutableArray alloc] initWithArray:[myView subviews]]; 
// Explicitly made mutable in an attempt to prevent Cocoa from returning 
// the same array, instead of making a copy. Another, tedious option would 
// be to create an empty mutable array and add the elements in subviews one by one. 

for(UIView* view in copyOfSubviews){ 
    if ([view isKindOfClass:[ComponentCustomView class]){ 
     [view removeFromSuperview]; 
    } 
} 

// (This is for non-ARC only:) 
[copyOfSubviews release]; 
相關問題