Skip to content

Instantly share code, notes, and snippets.

@scottjacksonx
Last active December 30, 2015 10:59
Show Gist options
  • Save scottjacksonx/7819383 to your computer and use it in GitHub Desktop.
Save scottjacksonx/7819383 to your computer and use it in GitHub Desktop.
Recursively walks a UIView's subview hierarchy looking for a view of the given kind. Any time we find a view of that kind, we execute the given block, passing in the view we found.
//
// UIView+RecursiveSubviews.h
//
// Created by Scott Jackson on 6/12/2013.
//
#import <UIKit/UIKit.h>
@interface UIView (RecursiveSubviews)
/**
Recursively looks at a view's subview hierarchy and executes the given block on each subview of the given class that's found.
@param class: the class of the subview you're trying to find
@param block: the block to perform when we've found a subview of the given class. Takes one parameter (a subview that was found in the search that's of the type you're looking for).
*/
- (void)findSubviewsOfType:(Class)class andExecuteBlock:(void (^)(id subview))block;
@end
//
// UIView+RecursiveSubviews.m
//
// Created by Scott Jackson on 6/12/2013.
//
#import "UIView+RecursiveSubviews.h"
@implementation UIView (RecursiveSubviews)
#pragma mark - Public
- (void)findSubviewsOfType:(Class)class andExecuteBlock:(void (^)(id subview))block {
[self findSubviewsOfType:class inSubviewHierarchyOfView:self andExecuteBlock:block];
}
#pragma mark - Private
- (void)findSubviewsOfType:(Class)class inSubviewHierarchyOfView:(UIView *)rootView andExecuteBlock:(void (^)(id subview))block {
for (UIView *v in rootView.subviews) {
if ([v isKindOfClass:class]) {
if (block) {
block(v);
}
}
[self findSubviewsOfType:class inSubviewHierarchyOfView:v andExecuteBlock:block];
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment