Nils
Nils

Reputation: 13777

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.

Upvotes: 5

Views: 4539

Answers (1)

Kyr Dunenkoff
Kyr Dunenkoff

Reputation: 8090

Try it like this, should be safe enough.

for (id subview in view.subviews) {
        if ([subview isMemberOfClass:viewType]) {
            block(subview);
        }
    }

Upvotes: 11

Related Questions