Reputation: 2735
Is there a way to set all UILabels as hidden in Objective-C? I'm showing and hiding labels based on if
statements and feel like I'm writing really bulky code. Is there a way to select all UILabels to setHidden:YES
a la CSS?
Edit: I need one of them visible at a time, not all hidden at once.
Thanks!
Upvotes: 1
Views: 2135
Reputation: 56809
If you only need 1 UILabel
at all time, you can reuse the same UILabel
. The advantage is you use a bit less memory and you don't need to manage all the UILabel
s. The disadvantage is that you need to recalculate/store the coordinates to put the UILabel
and stores the content of the UILabel
(the management is shifted to this).
Now that the requirement has changed, the below answer is no longer valid. However, I still keep it there, in case anyone wants to hide/show all labels.
I don't think you can do it like CSS, but we can use a trick to avoid having to loop through all the UILabel
s to setHidden
.
You can put all the UILabel
s as subview of a transparent UIView
. The size
and origin
of the transparent UIView
should be configured so that the coordinate is the same as when you don't use the transparent view (to avoid confusion). When you want to hide all UILabel
s, you can just hide the whole transparent UIView
.
This has a drawback is that all the UILabel
s must be on top or under the existing view. This means that you cannot freely adjust some label to be on top of certain element, and some label to be below certain element on the existing view. You need to create another view for that purpose, and things will get quite messy there.
Upvotes: 1
Reputation: 1029
If all your labels lay at the same view you can use it's subviews
property:
for (UIView *subview in self.view.subviews) {
if ([subview isKindOfClass:[UILabel class]]) {
subview.hidden = YES;
}
}
And if there are numerous of views with labels you can even add a category to the whole UIView
.
@interface UIView (HideLabels)
- (void)hideAllLabels:(BOOL)hide withExcludedLabel:(UILabel *)label;
@end
@implementation UIView (HideLabels)
- (void)hideAllLabels:(BOOL)hide withExcludedLabel:(UILabel *)label
{
for (UIView *subview in self.view.subviews) {
if (subview != label && [subview isKindOfClass:[UILabel class]]) {
subview.hidden = YES;
}
}
}
@end
There's no other way to do this.
Edit: the code above updated according to your needs.
Upvotes: 2