iOS开发中,调整view层级位置的两个属性

控件的层级关系和你加入到父视图的顺序有关,也就是先addsubview至父视图的,层级越低,会被后加入的遮盖。
可以通过以下函数改变子视图的层级:

1.Objective-C版本:
将UIView显示在最前面:
- (void)bringSubviewToFront:(UIView *)view;

将UIView显示在下面:
- (void)sendSubviewToBack:(UIView *)view;

2.Swift版本:
将UIView显示在最前面:
open func bringSubview(toFront view: UIView)

将UIView显示在下面:
open func sendSubview(toBack view: UIView)

下面我们来举个实例:
1.Objective-C的情况:

UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 150, 100, 100)];
    view1.backgroundColor = [UIColor redColor];
    [self.view addSubview:view1];

    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(150, 200, 100, 100)];
    view2.backgroundColor = [UIColor greenColor];
    [self.view addSubview:view2];

    // 以上显示:红色视图(view1)先添加,在下面,绿色视图(view2)后添加,在上面

如图:iOS开发中,调整view层级位置的两个属性_第1张图片
修改成如下代码:

UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(100, 150, 100, 100)];
    view1.backgroundColor = [UIColor redColor];
    [self.view addSubview:view1];

    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(150, 200, 100, 100)];
    view2.backgroundColor = [UIColor greenColor];
    [self.view addSubview:view2];

    // 以上显示:红色视图(view1)先添加,在下面,绿色视图(view2)后添加,在上面


    // 添加如下修改层级的代码

    // 将view2放在最下方
    [self.view sendSubviewToBack:view2];

    // 将view1放在最上方
    [self.view bringSubviewToFront:view1];

iOS开发中,调整view层级位置的两个属性_第2张图片
2.Swift的情况

let view1 = UIView(frame: CGRect(x: 100, y: 150, width: 100, height: 100))
        view1.backgroundColor = UIColor.red
        self.view.addSubview(view1)

        let view2 = UIView(frame: CGRect(x: 150, y: 200, width: 100, height: 100))
        view2.backgroundColor = UIColor.green;
        self.view.addSubview(view2)

        // 以上显示:红色视图(view1)先添加,在下面,绿色视图(view2)后添加,在上面


        // 添加如下修改层级的代码

        // 将view2放在最下方
        self.view.sendSubview(toBack: view2)

        // 将view1放在最上方
        self.view.bringSubview(toFront: view1)

它的效果这里不再说,效果和Objective-C的一样,读者也可以自己试一下。

你可能感兴趣的:(iOS开发)