如何删除以编程方式添加的自定义视图?

时间:2012-06-27 10:03:47

标签: iphone objective-c ios

在其中一个iPad应用程序中,我正在工作,我已将自定义视图添加到视图中。这工作正常,但现在我想删除添加的所有自定义视图。我该怎么做?

以下是我添加自定义视图的代码

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++;
}

3 个答案:

答案 0 :(得分:4)

您可以从父视图中删除ComponentCustomView类型的所有子视图

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

答案 1 :(得分:0)

NSArray  *arr = [self.view subViews];

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

答案 2 :(得分: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];