- (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];
// 如果沒(méi)有子視圖就直接返回
if ([subviews count] == 0) return;
for (UIView *subview in subviews) {
// 根據(jù)層級(jí)決定前面空格個(gè)數(shù),來(lái)縮進(jìn)顯示
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)];
}
}
打印結(jié)果

image.png