Hide UIView subviews

14,704

Solution 1

Objective-C (KVC)

[mainView.subviews setValue:@YES forKeyPath:@"hidden"];

Swift:

mainView.subviews.forEach { $0.isHidden = true }

Solution 2

If you want to hide all of the 600 subviews without creating a for loop, I think that there is another simple way as well. Look at the documentation for hidden property of UIView. It says:

A hidden view disappears from its window and does not receive input events. It remains in its superview’s list of subviews, however, and participates in autoresizing as usual. Hiding a view with subviews has the effect of hiding those subviews and any view descendants they might have. This effect is implicit and does not alter the hidden state of the receiver’s descendants.

So make a UIView (let's call it containerView) and make it a subview of your mainView. Then take all of your 600 subviews and make them subviews of containerView, not your mainView. You can now hide all 600 subviews (as well as containerView) with one simple line:

mainView.containerView.hidden=YES;

Your mainView will remain visible of course.

Share:
14,704
Prashanth Rajagopalan
Author by

Prashanth Rajagopalan

Updated on June 19, 2022

Comments

  • Prashanth Rajagopalan
    Prashanth Rajagopalan almost 2 years

    I have UIView which have n number of subviews. Let say n as 600 subviews. I know there is a way to hide all the subviews by the following code

    for (UIView *subView in mainView.subviews) {
    subView.hidden = YES;
    }
    

    But is there are any other proper way or API's to hide all the subviews.Thanks in advance.