猿问

如何遍历UIView的所有子视图及其子视图和子视图

如何遍历UIView的所有子视图及其子视图和子视图?



隔江千里
浏览 1445回答 3
3回答

天涯尽头无女友

使用递归:// UIView+HierarchyLogging.h@interface UIView (ViewHierarchyLogging)- (void)logViewHierarchy;@end// UIView+HierarchyLogging.m@implementation UIView (ViewHierarchyLogging)- (void)logViewHierarchy{    NSLog(@"%@", self);    for (UIView *subview in self.subviews)    {        [subview logViewHierarchy];    }}@end// In your implementation[myView logViewHierarchy];

明月笑刀无情

好了,这是我为UIView类使用递归和包装器(类别/扩展名)的解决方案。// UIView+viewRecursion.h@interface UIView (viewRecursion)- (NSMutableArray*) allSubViews;@end// UIView+viewRecursion.m@implementation UIView (viewRecursion)- (NSMutableArray*)allSubViews{   NSMutableArray *arr=[[[NSMutableArray alloc] init] autorelease];   [arr addObject:self];   for (UIView *subview in self.subviews)   {     [arr addObjectsFromArray:(NSArray*)[subview allSubViews]];   }   return arr;}@end用法:现在您应该遍历所有子视图并根据需要进行操作。//disable all text fieldsfor(UIView *v in [self.view allSubViews]){     if([v isKindOfClass:[UITextField class]])     {         ((UITextField*)v).enabled=NO;     }}

繁花如伊

Swift 3中的解决方案,subviews不包含视图本身就提供了所有功能:extension UIView {var allSubViews : [UIView] {        var array = [self.subviews].flatMap {$0}        array.forEach { array.append(contentsOf: $0.allSubViews) }        return array    }}
随时随地看视频慕课网APP
我要回答