iOS遍历打印所有子视图

- (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遍历打印所有子视图)