【小白搞iOS】3、iOS最基础的视图类UIView

2019-11-10  本文已影响0人  空杯_小白

什么是UIView

UIView主要处理的两件事

1.布局

2.管理子View

代码展示

    //创建视图1
    UIView*view1 = [[UIView alloc]init];
    //视图1添加红色背景
    view1.backgroundColor = [UIColor redColor];
    //确定视图1的位置
    view1.frame = CGRectMake(100, 100, 100, 100);
    //添加到父视图
    [self.view addSubview:view1];
    
    //创建视图2
    UIView*view2 = [[UIView alloc]init];
    //视图2添加绿色背景
    view2.backgroundColor = [UIColor greenColor];
    //确定视图2的位置
    view2.frame = CGRectMake(150, 150, 100, 100);
    //添加到父视图
    [self.view addSubview:view2];
显示效果.png
从图片可以看出先添加view1再添加view2,view1先入栈,view2再入栈,view和view2重叠的位置,显示view2的。位置重叠的展示最后入栈的

UIView生命周期

1.UIView类方法

iOS UIView类扩展方法.png

上图所示iOS中UIView的类方法。其中包括之前说的添加子视图(addSubview)等。对于UIView生命周期我们只需关注以下四个方法

- (void)willMoveToSuperview:(nullable UIView *)newSuperview;
- (void)didMoveToSuperview;
- (void)willMoveToWindow:(nullable UIWindow *)newWindow;
- (void)didMoveToWindow;

为了更好的展示UIView从创建到被展示的内部流程。用TestView继承UIView

@interface TestView : UIView
@end
@implementation TestView
@end

重载一下UIView 生命周期的方法,为了更好的观察执行顺序,将方法名称在控制台打印出来。(最好使用断点来观察方法执行顺序)

@interface TestView : UIView
@end

@implementation TestView

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    NSLog(@"init");
    return self;
}

- (void)willMoveToSuperview:(nullable UIView *)newSuperview{
    [super willMoveToSuperview:newSuperview];
    NSLog(@"willMoveToSuperview");
}
- (void)didMoveToSuperview{
    [super didMoveToSuperview];
    NSLog(@"didMoveToSuperview");
}
- (void)willMoveToWindow:(nullable UIWindow *)newWindow{
    [super willMoveToSuperview:newWindow];
    NSLog(@"willMoveToWindow");
}
- (void)didMoveToWindow{
    [super didMoveToWindow];
    NSLog(@"didMoveToWindow");
}
@end

初始化一个TestView

    //创建视图1
    TestView*view1 = [[TestView alloc]init];
    //视图1添加红色背景
    view1.backgroundColor = [UIColor redColor];
    //确定视图1的位置
    view1.frame = CGRectMake(100, 100, 100, 100);
    //添加到父视图
    [self.view addSubview:view1];

运行程序观察控制台打印结果

运行结果.png
观察控制台可知UIView的生命周期:
init
willMoveToSuperview
didMoveToSuperview
willMoveToWindow
didMoveToWindow

UIView的生命周期按照上面顺序执行,并且willMoveToSuperview和didMoveToSuperview、willMoveToWindow和didMoveToWindow成对出现。

上一篇下一篇

猜你喜欢

热点阅读