UIView 查找subview 和 层次

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010209842/article/details/64591941

    CGRect frame =  [[UIScreen mainScreen] bounds];
    
    UIView *views = [[UIView alloc]init];
    views.frame = CGRectMake(10, 30,frame.size.width-20 , frame.size.height-20-20);
    views.backgroundColor = [UIColor blueColor];
    [self.view addSubview:views];
    
    UIView *superView = views.superview;
    superView.backgroundColor = [UIColor greenColor];
    
    UIView *view1 = [[UIView alloc]init];
    view1.tag = 1;
    view1.frame = CGRectMake(20, 20, 30, 30);
    view1.backgroundColor = [UIColor yellowColor];
    [views addSubview:view1];
    
    UIView *view2 = [[UIView alloc]init];
    view2.tag = 2;
    view2.frame = CGRectMake(30,30, 100, 20);
    view2.backgroundColor = [UIColor purpleColor];
    view2.alpha= 5.0f;
    [views addSubview:view2];
    
    //找子视图的方法
    NSArray *subviews = [views subviews];
    for (UIView *uiView in subviews) {
        if ([uiView tag] == 1) {
            uiView.backgroundColor = [UIColor whiteColor];
        }
    }
    
    //查找子视图的方法
    UIView *subView = [views viewWithTag:2];
    subView.backgroundColor = [UIColor grayColor];
    
    //交换两个层的视图
    [views exchangeSubviewAtIndex:1 withSubviewAtIndex:0];
    
    UIView *view3 = [[UIView alloc]init];
    view3.frame = CGRectMake(20, 20, 60, 60);
    view3.backgroundColor = [UIColor blackColor];
    //指定插入某个层
    [views insertSubview:view3 atIndex:1];
    [views insertSubview:view3 aboveSubview:views];
    [views insertSubview:view3 belowSubview:view1];
    //直接放到最顶层或最底层
    [views bringSubviewToFront:view3];
    [views sendSubviewToBack:view3];


获取 父类view 控件

UIView *superView = views.superview;


查找子视图的方法

方法1:

通过父类调用subviews方法,获取所有子类view的数组,根据条件找到指定的subview

    NSArray *subviews = [viewssubviews];

    for (UIView *uiViewin subviews) {

        if ([uiViewtag] == 1) {

            uiView.backgroundColor = [UIColorwhiteColor];

        }

    }

方法2:

通过对view设置tag,并通过父控件调用 viewWithTag方法获取指定subView

    UIView *subView = [viewsviewWithTag:2];

    subView.backgroundColor = [UIColorgrayColor];


交换两个层的视图

通过调用方法,可以讲子view的视图层交换位置    

[views exchangeSubviewAtIndex:1withSubviewAtIndex:0];


指定插入某个层    

将控件插入指定的层

    UIView *view3 = [[UIViewalloc]init];

    view3.frame =CGRectMake(20,20, 60,60);

    view3.backgroundColor = [UIColorblackColor];

    //指定插入某个层

    [views insertSubview:view3atIndex:1];//插入在位置1

    [views insertSubview:view3aboveSubview:views];//插入在views的最上层

    [views insertSubview:view3belowSubview:view1];//插入在views的最下层


直接放到最顶层或最底层

将view3移到最顶层或最底层    

    [views bringSubviewToFront:view3];

    [views sendSubviewToBack:view3];





猜你喜欢

转载自blog.csdn.net/u010209842/article/details/64591941