美文网首页
iOS遍历打印所有子视图

iOS遍历打印所有子视图

作者: ngugg | 来源:发表于2019-05-27 15:34 被阅读0次
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = UIColor.whiteColor;
        
        UILabel *label = [UILabel new];
        UIButton *button = [UIButton new];
        
        UIImageView *imageView = [UIImageView new];
        UIView *view1 = [UIView new];
        UIView *view2 = [UIView new];
        
        [self.view addSubview:label];
        [self.view addSubview:button];
        [button addSubview:imageView];
        [imageView addSubview:view1];
        [imageView addSubview:view2];
        
        // 打印所有子视图
     [self getSub:self.view andLevel:1];
        
    }
    
    // 递归获取子视图
    - (void)getSub:(UIView *)view andLevel:(int)level {
        NSArray *subviews = [view subviews];
        
        // 如果没有子视图就直接返回
        if ([subviews count] == 0) return;
        
        for (UIView *subview in subviews) {
            
            // 根据层级决定前面空格个数,来缩进显示
            NSString *blank = @"";
            for (int i = 1; i < level; i++) {
                blank = [NSString stringWithFormat:@"  %@", blank];
            }
            
            // 打印子视图类名
            NSLog(@"%@%d: %@", blank, level, subview.class);
            
            // 递归获取此视图的子视图
            [self getSub:subview andLevel:(level+1)];
            
        }
    }
    
    

    打印结果

    image.png

    参考:https://blog.csdn.net/Cloudox_/article/details/64132566

    相关文章

      网友评论

          本文标题:iOS遍历打印所有子视图

          本文链接:https://www.haomeiwen.com/subject/qbuhtctx.html