How can I loop through all subviews of a UIView, and their subviews and their subviews

123hal321 picture 123hal321 · Apr 30, 2010 · Viewed 84.3k times · Source

How can I loop through all subviews of a UIView, and their subviews and their subviews?

Answer

Ole Begemann picture Ole Begemann · Apr 30, 2010

Use recursion:

// UIView+HierarchyLogging.h
@interface UIView (ViewHierarchyLogging)
- (void)logViewHierarchy;
@end

// UIView+HierarchyLogging.m
@implementation UIView (ViewHierarchyLogging)
- (void)logViewHierarchy
{
    NSLog(@"%@", self);
    for (UIView *subview in self.subviews)
    {
        [subview logViewHierarchy];
    }
}
@end

// In your implementation
[myView logViewHierarchy];