UIView 添加子视图的常用方法

1.  - (void)addSubview:(UIView *)view 这是最常用的方法有两个注意点

  • 参数view可以是nil,运行不会报错,当然,父视图的subViews也不会增加。
  • 此方法增加的view层级当前是最高的,也就是最靠外。

2.  - (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;

  • 父视图的所有的子视图的index默认是从0开始的。
  • index如果赋了负数,执行不会报错,但添加会失败。
  • 如果index值过大,能正常添加subView,但传入index会无效,相当于执行第一种添加方法
1     UILabel *testLbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
2     [testLbl setText:@"test"];
3     
4     UIView *testV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
5     testV.backgroundColor = [UIColor greenColor];
6 
7     [self.window insertSubview:testV atIndex:5];
8     [self.window insertSubview:testLbl atIndex:4];
Index值过大代码示例

    以上代码中靠前的是testLbl。

3.  - (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;

  •  参数siblingSubview如果是nil,执行不会报错,但添加会失败
[self.window insertSubview:testLbl aboveSubview:nil];

4.  - (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;

  •  和3相同。
原文地址:https://www.cnblogs.com/ieso-ios/p/5115795.html