0

在其中一个 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++;
}
4

3 回答 3

4

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

for (UIView *view in self.formConatinerView.subviews) {
    if ([view isKindOfClass:[ComponentCustomView class]) {
        [view removeFromSuperview];
    }
}
于 2012-06-27T10:05:27.660 回答
0
NSArray  *arr = [self.view subViews];

for (UIView *view in arr) {
    if ([view isKindOfClass:[ComponentCustomView class]) {
        [view removeFromSuperview];
    }
}
于 2012-06-27T10:14:17.953 回答
0

我不确定从正在迭代的数组中删除对象(在这种情况下subviews)是否安全(我记得读过一些关于 Mac OS X 和 iOS 之间差异的文章,但不确定......);除非 propertysubviews返回内部数组的副本(很可能因为内部数组需要是可变的),否则 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]; 
于 2012-06-27T10:21:16.027 回答