当我的应用程序回到它的根视图控制器,在viewDidAppear:方法中,我需要删除所有子视图。

我该怎么做呢?


当前回答

在Swift中,你可以使用这样的函数式方法:

view.subviews.forEach { $0.removeFromSuperview() }

作为比较,命令式方法看起来像这样:

for subview in view.subviews {
    subview.removeFromSuperview()
}

这些代码片段只适用于iOS / tvOS,但在macOS上略有不同。

其他回答

为了从父视图中移除所有子视图:

NSArray *oSubView = [self subviews];
for(int iCount = 0; iCount < [oSubView count]; iCount++)
{
    id object = [oSubView objectAtIndex:iCount];
    [object removeFromSuperview];
    iCount--;
}

为了删除所有子视图

- (void)makeObjectsPerformSelector:(SEL)aSelector;

用法:

[self.View.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

该方法存在于NSArray.h文件中,并使用NSArray(NSExtendedArray)接口

在monotouch / xamarin。这对我来说很管用:

SomeParentUiView.Subviews.All(x => x.RemoveFromSuperview);

对于使用自动布局的ios6,我不得不添加一些代码来消除限制。

NSMutableArray * constraints_to_remove = [ @[] mutableCopy] ;
for( NSLayoutConstraint * constraint in tagview.constraints) {
    if( [tagview.subviews containsObject:constraint.firstItem] ||
       [tagview.subviews containsObject:constraint.secondItem] ) {
        [constraints_to_remove addObject:constraint];
    }
}
[tagview removeConstraints:constraints_to_remove];

[ [tagview subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

我相信还有更简洁的方法,但这对我来说很管用。在我的情况下,我不能使用直接[tagview removeConstraints:tagview。因为在XCode中设置了一些被清除的约束。

view.subviews.forEach { $0.removeFromSuperview() }