Question

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.

Was it helpful?

Solution

Objective-C (KVC)

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

Swift:

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top