当我的应用程序返回到其根视图控制器时,在viewDidAppear:
方法中我需要删除所有的子视图。
我该如何做?
subviews.map { $0.removeFromSuperview }
makeObjectsPerformSelector
,但具有稍微更多的类型安全性。- (void)makeObjectsPerformSelector:(SEL)aSelector;
使用方法:
[self.View.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
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.constraints]
,因为在XCode中设置了一些约束条件,这些条件会被清除。
为了从父视图中移除所有子视图:
NSArray *oSubView = [self subviews];
for(int iCount = 0; iCount < [oSubView count]; iCount++)
{
id object = [oSubView objectAtIndex:iCount];
[object removeFromSuperview];
iCount--;
}
iCount++
和 iCount--
操作,但是索引值保持不变,如果 [oSubView count]>0
,那么程序将会进入无限循环。这明显是有缺陷的,并且 不能使用 。 - Daniel
map
不应该产生副作用。此外,通过forEach
可以实现相同的结果。 - Cristik