当以编程方式添加视图时,
addSubview
和insertSubView
方法之间的区别是什么?addSubview
和insertSubView
方法之间的区别是什么?唯一的区别在于添加视图的位置:是最前面的视图 (addSubview:
),还是第五个子视图之前 (insertSubview:atIndex:
),或者是紧接在另一个子视图后面 (insertSubview:aboveSubview:
)。
使用insertSubView:
方法可以指定视图的索引,从而决定视图在z轴上的顺序。索引越高的视图会覆盖在索引较低的视图之上。
我认为它们没有区别。addSubview:
只是一个方便的方法。
[view insertSubview:aView atIndex:[view.subviews count]]
1.addSubview 将子视图添加到数组中,然后添加到视图的图层中
- (void)addSubview:(UIView *)subview
{
[_subviews addObject:subview];
[_layer addSublayer:subview.layer];
}
}
2. 在执行 insertSubview 操作后,将您的视图添加为子视图,然后调用
[_layer insertSublayer:subview.layer atIndex:index];
- (void)insertSubview:(UIView *)subview atIndex:(NSInteger)index
{
[self addSubview:subview];
[_layer insertSublayer:subview.layer atIndex:index];
}