首页 > 学院 > 开发设计 > 正文

addSubview和insertSubview 区别

2019-11-09 16:14:53
字体:
来源:转载
供稿:网友

子视图是以栈的方式存放的,也就是说有层次的存放 addSubview: addsubview时都是在最上面面添加 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];

看到如下效果 addSubview

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];

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

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

打印如下:

2017-02-08 10:10:07.310 sa1[1058:39734] ( "<_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。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表