Remove all subviews?

2020-01-25 03:07发布

When my app gets back to its root view controller, in the viewDidAppear: method I need to remove all subviews.

How can I do this?

标签: ios subview
15条回答
一夜七次
2楼-- · 2020-01-25 03:41

Get all the subviews from your root controller and send each a removeFromSuperview:

NSArray *viewsToRemove = [self.view subviews];
for (UIView *v in viewsToRemove) {
    [v removeFromSuperview];
}
查看更多
祖国的老花朵
3楼-- · 2020-01-25 03:43

Try this way swift 2.0

view.subviews.forEach { $0.removeFromSuperview() }
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-01-25 03:44

For ios6 using autolayout I had to add a little bit of code to remove the constraints too.

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)];

I'm sure theres a neater way to do this, but it worked for me. In my case I could not use a direct [tagview removeConstraints:tagview.constraints] as there were constraints set in XCode that were getting cleared.

查看更多
Bombasti
5楼-- · 2020-01-25 03:46

In Swift you can use a functional approach like this:

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

As a comparison, the imperative approach would look like this:

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

These code snippets only work in iOS / tvOS though, things are a little different on macOS.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-01-25 03:46

Using Swift UIView extension:

extension UIView {
    func removeAllSubviews() {
        for subview in subviews {
            subview.removeFromSuperview()
        }
    }
}
查看更多
家丑人穷心不美
7楼-- · 2020-01-25 03:46
view.subviews.forEach { $0.removeFromSuperview() }
查看更多
登录 后发表回答