Dipankar Choudhary
Dipankar Choudhary

Reputation: 11

How to iterate through self.superview in Xcode?

I have a class called LabelView inheriting from UIView. In the story board have a view dragged and inheriting from LabelView. Now I want to iterate through the self.superview to set the attributed text of each view. Please suggest a method to do so. Here is my code:

int i=0;
    for (UIView *view in labelView) {
        if ([view isMemberOfClass:[LabelView class]]) {
            [view setTag:i];
            NSArray *symbols = @[@"+", @"-", @"*", @"/"];
            NSString* symb = [NSString stringWithFormat:@"%@", [symbols objectAtIndex:i]];
            UIFont *labelFont = [UIFont systemFontOfSize:view.bounds.size.width*0.80];
            NSAttributedString *labelOperator=[[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@", symb]attributes:@{NSFontAttributeName: labelFont}];
            CGRect textrect;
            textrect.origin=CGPointMake(12, 0);
            textrect.size=[labelOperator size];
            [labelOperator drawInRect:textrect];
            i++;
        }
        else{
            NSLog(@"fail");
        }

}

Upvotes: 0

Views: 643

Answers (2)

Mundi
Mundi

Reputation: 80271

The key is to go from your label view to the superview and iterate through its subviews.

for (UIView *label in labelView.superview.subviews) {
   if ([label isKindOfClass:[LabelView class]]) {
       // configure the label
   }
}

Upvotes: 0

GenieWanted
GenieWanted

Reputation: 4513

You may want to try something like this:

for (UIView *view in self.view.subviews) {
        if ([view isMemberOfClass:[LabelView class]]) {
//DO WHATEVER YOU WANT
}

The above fast enumeration code iterates through all the subviews in your self.view and checks if the view is a member of your custom class which is LabelView. If it finds one, then the statements inside the if condition gets executed. Hope it helps!

Upvotes: 1

Related Questions