Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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