Dipankar Choudhary
Dipankar Choudhary

Reputation: 11

How to find number of subviews?

I have a Xcode project and in it i have dragged two views and both of them inherit from a class LabelsView. However when I try and run the code to find out number of subviews, I get 4. Can anyone explain why is this happening. The code is

NSLog(@"no. of subviews:%@",[NSString stringWithFormat:@"%d",[self.superview.subviews count]]);

Upvotes: 0

Views: 1436

Answers (2)

Jobeso
Jobeso

Reputation: 733

If you want the amount of all subviews in swift, you can just go with

self.subviews.count

Upvotes: 1

Alexander
Alexander

Reputation: 583

You're probably getting a weird subview count because you're accessing self.superview.subviews. You likely just want self.subviews.

If, like you said, you only care about subviews of type LabelsView, you can filter those out like this:

int labelViewCount = 0;
for(LabelsView *subview in self.subviews) {

    if([subview isKindOfClass:[LabelsView class]]) {
         labelViewCount++;
    }
}
NSLOG(@"label count: %d", labelViewCount);

Upvotes: 3

Related Questions