UIView的层次关系

来源:互联网 发布:ubuntu安装中文界面 编辑:程序博客网 时间:2024/05/22 12:14

//添加子视图

UIView *fatherView = [[UIView alloc] initWithFrame:CGRectMake(100, 200, 200, 200)];fatherView.backgroundColor = [UIColor redColor];[self.view addSubview:fatherView];//子视图1 绿色UIView *sonView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];sonView.backgroundColor = [UIColor greenColor];sonView.tag = 100;[fatherView addSubview:sonView];//子视图2 蓝色UIView *sonView2 = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];sonView2.backgroundColor = [UIColor blueColor];sonView2.tag = 101;[fatherView addSubview:sonView2];//子视图3 黑色UIView *sonView3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];sonView3.backgroundColor = [UIColor blackColor];[fatherView addSubview:sonView3];//子视图4 青色UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, 100, 100)];label.backgroundColor = [UIColor cyanColor];[fatherView addSubview:label];

//获取父视图

UIView *view = sonView.superview;NSLog(@"father == %@",NSStringFromCGRect(view.frame));

//获取子视图

NSLog(@"count == %ld",fatherView.subviews.count);for(UIView *view in fatherView.subviews){    if (view.tag == 100) {        NSLog(@"sonView");    }    if(view.tag == 101){        NSLog(@"sonView2");    }    if ([view isKindOfClass:[UILabel class]]) {        NSLog(@"label");    }}

//把一个子视图移动到最前端

[fatherView bringSubviewToFront:sonView];

//删除一个子视图

[sonView removeFromSuperview];UIView *sonView5 = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)];sonView5.backgroundColor = [UIColor purpleColor];[fatherView addSubview:sonView5];

//截掉超出父视图部分的子视图

fatherView.clipsToBounds = YES;

//隐藏视图

fatherView.hidden = NO;

//检测视图之间的关系

BOOL ret = [sonView2 isDescendantOfView:fatherView];NSLog(@"ret == %@",ret ? @"YES":@"NO");

//交换子视图层次关系

[fatherView exchangeSubviewAtIndex:0 withSubviewAtIndex:2];UIView *sonView4 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];sonView4.backgroundColor = [UIColor yellowColor];

//在特定位置插入一个视图

[fatherView insertSubview:sonView4 atIndex:3];
0 0
原创粉丝点击