Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over all subviews of a specific type

Iterating over all UIViews in the subviews of a class and then checking the type in the loop using isKindOfClass made my code look redundant. So I wrote the following method which executes a block for each subview.

@implementation Util

+ (void)iterateOverSubviewsOfType:(Class)viewType 
                   view:(UIView*)view
                   blockToExecute:(void (^)(id subview))block
{
    for (UIView* subview in view.subviews) {
        if ([subview isKindOfClass:viewType]) {
            block(subview);
        }
    }
}

@end

The block passed to this method takes an argument of type id. The type used here should be of course the same as passed as the first argument. However so far I haven't figured out a way to make this more type safe.

like image 509
Nils Avatar asked Jan 25 '12 09:01

Nils


1 Answers

Try it like this, should be safe enough.

for (id subview in view.subviews) {
        if ([subview isMemberOfClass:viewType]) {
            block(subview);
        }
    }
like image 179
Kyr Dunenkoff Avatar answered Sep 28 '22 03:09

Kyr Dunenkoff