How to get all UILabels in a UIView

I need a way to get all UILabel inside a UIView without having to view all the views in a UIView .

I have many other types of views, UIButton s, UIImageView , and it would take too long to go through all of them when I just need UILabel s.

I am trying to avoid something like this:

 for (UIView *view in myView.subviews) { if([view isKindOfClass:[UILabel class]]) { UILabel *lbl = (UILabel*)view; } } 

Is this possible or is I dreaming?

+7
source share
4 answers

Create an NSArray ivar that you can add all UILabel to.

If you do this in code, then when creating a UILabel just do

 NSMutableArray *labels = [[NSMutableArray alloc] init]; // Repeat this for al labels UILabel *label = [[UILabel alloc] in... [labels addObject:label]; // Then self.labels = [labels copy]; 

If you are using IB, declare your property as follows

 @property (nonatomic, strong) IBOutletCollection(UILabel) NSArray *labels; 

and connect all the tags before that.

+5
source

Man, you need to use recursion. (If you do not want to use usage tags)

Try it.

 -(UIView *)checkChild:(UIView *)view{ NSArray *arrayView = view.subviews; UIView *returnView = nil; for (UIView *auxView in arrayView) { if ([auxView isKindOfClass:[UILabel class]]) { return auxView; }else{ returnView = [self checkChild:auxView]; } } return returnView; } 
+4
source

You can set the tag property for the label .. something like this ...

 label.tag = 100; UILabel *lbl = [yourView viewWithTag:100]; 
+1
source

I liked the @SiddharthaMoraes approach, but he modified it to collect all the elements found in his path. I searched for UILabels inside my UIViewController and could not find them because they are nested inside another UIView , so this recursion should solve the problem:

 -(NSMutableArray *)checkChild:(UIView *)view{ NSArray *arrayView = view.subviews; NSMutableArray *arrayToReturn = [NSMutableArray new]; for (UIView *auxView in arrayView) { if ([auxView isKindOfClass:[MyLabel class]]) { [arrayToReturn addObject:auxView]; }else if( auxView.subviews ){ [arrayToReturn addObjectsFromArray:[self checkChild:auxView]]; } } return arrayToReturn; } 
+1
source

All Articles