16

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.

Prashanth Rajagopalan
  • 718
  • 1
  • 10
  • 27

2 Answers2

41

Objective-C (KVC)

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

Swift:

mainView.subviews.forEach { $0.isHidden = true }
rfrittelli
  • 1,211
  • 13
  • 15
  • Thanks, It works. Is this is the proper and better way to code other than the for loop ? – Prashanth Rajagopalan Oct 17 '13 at 19:02
  • 1
    I'm not sure if it's proper or better per se, but kvc/kvo gives you a lot of power to reduce your code base. Check out http://nshipster.com/kvc-collection-operators/ and http://nshipster.com/key-value-observing/ will help you understand how you can make use of this in the future. – rfrittelli Oct 17 '13 at 19:25
  • 1
    This is a nice, brief solution, but KVC isn't magic: it'll still have to iterate over the whole array of subviews setting the `hidden` property for each one. Putting all the subviews that need to be hidden in a container view and hiding that avoids the need to touch every subview when you want to hide them all. – Caleb Feb 01 '18 at 15:20
15

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.

Samuel W.
  • 370
  • 1
  • 10