谈谈addSubview和insertSubview

作者: Dwyane_Coding | 来源:发表于2017-02-14 18:02 被阅读181次

子视图是以栈的方式存放的,也就是说有层次的存放

addSubview:

addsubview时都是在最上面面添加

eg:

UIView *v1 = [UIView new];

v1.frame= CGRectMake(100,100,100,60);

v1.backgroundColor= [UIColor redColor];

UIView *v2 = [UIViewnew];

v2.backgroundColor= [UIColor purpleColor];

v2.frame= CGRectMake(80,120,100,60);

[self.view addSubview:v1];

[self.view addSubview:v2];

看到如下效果

pic1

insertSubview

insertSubView可以控制将view添加到指定的层

eg:

UIView *v1 = [UIView new];

v1.frame= CGRectMake(100,100,100,60);

v1.backgroundColor= [UIColor redColor];

UIView *v2 = [UIView new];

v2.backgroundColor= [UIColor purpleColor];

v2.frame= CGRectMake(80,120,100,60);

[self.view addSubview:v1];

[self.view addSubview:v2];

UIView*v3 = [UIView new];

v3.backgroundColor= [UIColor yellowColor];

v3.frame= CGRectMake(60,140,160,60);

[self.view insertSubview:v3 atIndex:3];
pic2

可以看到v3在v1跟v2之间,按照我们的打算,atIndex:3 应该是在第四层,而现在感觉不像,我们可以打印一下看下究竟:

NSLog(@"%@",self.view.subviews);

打印如下:

(
"<_UILayoutGuide: 0x7f8893602e80; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x60800003e220>>",
"<_UILayoutGuide: 0x7f8893609080; frame = (0 0; 0 0); hidden = YES; layer = <CALayer: 0x60800003e080>>",
"<UIView: 0x7f8893406ab0; frame = (100 100; 100 60); layer = <CALayer: 0x60000003de40>>",
"<UIView: 0x7f8893407270; frame = (60 140; 160 60); layer = <CALayer: 0x60000003dc00>>",
"<UIView: 0x7f8893407c60; frame = (80 120; 100 60); layer = <CALayer: 0x60000003de60>>"
)

可以看到v1之前,也就是self.view有两层,v1 index就是2, v2的为4,v3 插在 index:3 ,所以在v1跟v2之间。

可以看到:

[self.view addSubView:xx.view]其实就等于[self.view insertSubView:xx.view atIndex:[self.view.subViews count]];

即在最顶层添加view。

相关文章

网友评论

    本文标题:谈谈addSubview和insertSubview

    本文链接:https://www.haomeiwen.com/subject/ptqfwttx.html