Bartu
Bartu

Reputation: 2210

iterating through subviews - how to reach to all UI objects

I have created a xib file for my custom UIView and loaded my xib into my custom UIView with;

NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"ProductDetailView" owner:self options:nil];
self = [views objectAtIndex:0];

I didn't wanted to define all my subviews as IBOutlets, so instead I thought iterating through subviews would be more appropriate.

        for (id subview in self.subviews) {
            if ([subview isKindOfClass:[UIView class]]) {
                UIView *theView = (UIView*)subview;
                if (theView.tag == 16) {
                    // tag 16 is specific to some UIViews... do stuff
                }
            }
            else if ([subview isKindOfClass:[UILabel class]]) {
                UILabel *theLabel = (UILabel*)subview;

                if (theLabel.tag == 21) {
                    // tag 17 is specific to some UILabels... do stuff
                }
                else
                {
                    // no tag... do stuff 
                }

            }
        }

I thought this would be more robust, however since UILabels are inherited from UIViews, I cannot use this approach. I am aware that changing the if orders can make it work, but its not feeling very good to depend on the order if-clauses

What I am asking is, what would be the most logical approach in such situation? Should I be using viewWithTag: function instead of looping through id s and casting?

Upvotes: 1

Views: 1788

Answers (2)

Jaybit
Jaybit

Reputation: 1864

You can use IBOutletCollection. You create an Array of UILabels and an Array of UIViews

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

All you have to do to use this is create the @property above and in IB connect all the labels you want grouped to this collection just as you would for a IBOutlet. WHen you want to iterate through them:

for (UILabel *label in self.labels) {
     NSLog(@"labelTag:%i", label.tag);
     // Do what you want with this label
}

for (UIView *view in self.views) {
     NSLog(@"viewTag:%i", view.tag);
     // Do what you want with this view
}

Upvotes: 5

trojanfoe
trojanfoe

Reputation: 122458

If you want to test the specific type of an object then use isMemberOfClass rather than isKindOfClass, which tests if an object is of the specified class or inherits from the specified class.

Upvotes: 3

Related Questions