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

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


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];


Well here is my solution using recursion and a wrapper(category/extension) for the UIView class.

// UIView+viewRecursion.h@interface UIView (viewRecursion)- (NSMutableArray*) allSubViews;@end// UIView+viewRecursion.m@implementation UIView (viewRecursion)- (NSMutableArray*)allSubViews{   NSMutableArray *arr=[[[NSMutableArray alloc] init] autorelease];   [arr addObject:self];   for (UIView *subview in self.subviews)   {     [arr addObjectsFromArray:(NSArray*)[subview allSubViews]];   }   return arr;}@end

Usage : Now you should be looping through all the sub views and manipulate them as needed.

//disable all text fieldsfor(UIView *v in [self.view allSubViews]){     if([v isKindOfClass:[UITextField class]])     {         ((UITextField*)v).enabled=NO;     }}


Here's another Swift implementation:

extension UIView {    var allSubviews: [UIView] {        return self.subviews.flatMap { [$0] + $0.allSubviews }    }}