Skip to content

Instantly share code, notes, and snippets.

@nick-merrill
Last active August 29, 2015 13:56
Show Gist options
  • Save nick-merrill/8871969 to your computer and use it in GitHub Desktop.
Save nick-merrill/8871969 to your computer and use it in GitHub Desktop.
This is a convenience function to recursively run code on subviews of specified class types. It's untested, so please just use as a basis for something likely better, perhaps that includes IndexPath counting, etc.
/*
Example use:
// Return all labels of the cell
NSMutableArray *labels = [Utility ApplyToSubviews:cell limitedToClass:[UILabel class] usingBlock:^(id obj) {
UILabel *label = (UILabel *)obj;
label.text = @"Changed text";
} recursively:YES];
*/
/*************************************************************
Pass nil as LimitingClass if objects of all class types
should be included.
Pass nil as blockToApply to not run a block.
**************************************************************/
+ (NSMutableArray *)ApplyToSubviews:(UIView *)superview
limitedToClass:(Class)LimitingClass
usingBlock:(void (^)(id obj))blockToApply
recursively:(BOOL)isRecursive
{
return [Utility RecursiveApplyToSubviews:superview
limitedToClass:LimitingClass
usingBlock:blockToApply
withCurrentObjects:[NSMutableArray arrayWithCapacity:0]
recursively:isRecursive];
}
+ (NSMutableArray *)RecursiveApplyToSubviews:(UIView *)superview
limitedToClass:LimitingClass
usingBlock:(void (^)(id))blockToApply
withCurrentObjects:(NSMutableArray *)currentObjectsOfClass
recursively:(BOOL)isRecursive
{
NSArray *subviews = superview.subviews;
if (![subviews count]) {
return currentObjectsOfClass;
}
NSMutableArray *objectsOfClass = [NSMutableArray arrayWithCapacity:0];
[subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (LimitingClass == nil ||
[obj isKindOfClass:[LimitingClass class]]) {
[objectsOfClass addObject:obj];
if (blockToApply) {
blockToApply(obj); // apply block to object
}
}
if (isRecursive && [obj isKindOfClass:[UIView class]]) {
NSMutableArray *newObjects = [Utility RecursiveApplyToSubviews:((UIView *)obj) limitedToClass:LimitingClass usingBlock:blockToApply withCurrentObjects:currentObjectsOfClass recursively:isRecursive];
[objectsOfClass addObjectsFromArray:newObjects];
}
}];
return objectsOfClass;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment