Skip to content

Instantly share code, notes, and snippets.

@albertodebortoli
Created September 21, 2013 20:18
Show Gist options
  • Save albertodebortoli/6653791 to your computer and use it in GitHub Desktop.
Save albertodebortoli/6653791 to your computer and use it in GitHub Desktop.
Find the first view of a given class in the iOS7 subviews hierarchy. iOS backward compatible.
//
// UIView+ADBSubviews.h
// iHarmony
//
// Created by Alberto De Bortoli on 06/08/13.
// Copyright (c) 2013 iHarmony. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIView (ADBSubviews)
/**
* Recursively search for and return a view of a given class in the subviews hierarchy of the receiver
* searching for it at 3 level max deepness.
*
* @param clazz The given class.
*
* @return The first view of a given class found in the subviews hierarchy.
*/
- (id)firstSubviewOfClass:(Class)clazz;
/**
* Recursively search for and return a view of a given class in the subviews hierarchy of the receiver.
*
* @param clazz The given class.
* @param deepness The max level of recursion.
*
* @return The first view of a given class found in the subviews hierarchy.
*/
- (id)firstSubviewOfClass:(Class)clazz maxDeepnessLevel:(NSInteger)deepness;
@end
//
// UIView+ADBSubviews.m
// iHarmony
//
// Created by Alberto De Bortoli on 06/08/13.
// Copyright (c) 2013 iHarmony. All rights reserved.
//
#import "UIView+ADBSubviews.h"
@implementation UIView (ADBSubviews)
- (id)firstSubviewOfClass:(Class)clazz
{
return [self firstSubviewOfClass:clazz maxDeepnessLevel:3];
}
- (id)firstSubviewOfClass:(Class)clazz maxDeepnessLevel:(NSInteger)deepness
{
if (deepness == 0) {
return nil;
}
NSInteger count = deepness;
NSArray *subviews = self.subviews;
while (count > 0) {
for (UIView *v in subviews) {
if ([v isKindOfClass:clazz]) {
return v;
}
}
count--;
for (UIView *v in subviews) {
UIView *retVal = [v firstSubviewOfClass:clazz maxDeepnessLevel:count];
if (retVal) {
return retVal;
}
}
}
return nil;
}
@end
@albertodebortoli
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment