iOS View 生命周期

2019-08-29 10:24:24 浏览数 (1)

现在来看看View的生命周期

显示过程

-(void)willMoveToSuperview:(UIView *)newSuperview -(void)didMoveToSuperview

-(void)willMoveToWindow:(UIWindow *)newWindow -(void)didMoveToWindow

-(void)layoutSubviews

移除过程

-(void)willMoveToSuperview:(UIView *)newSuperview -(void)willMoveToWindow:(UIWindow *)newWindow

-(void)didMoveToWindow -(void)didMoveToSuperview

-(void)dealloc

验证

代码语言:javascript复制
#import "TestView.h"

@implementation TestView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self){
        NSLog(@"initWithFrame");
    }
    return self;
}

//(superview)
- (void)willMoveToSuperview:(UIView *)newSuperview{
     NSLog(@"willmovetosuperview");
    [super willMoveToSuperview:newSuperview];
}

- (void)didMoveToSuperview{
    NSLog(@"didmovetosuperview");
    [super didMoveToSuperview];
}

//(window)
- (void)willMoveToWindow:(UIWindow *)newWindow{
     NSLog(@"willmovetowindow");
    [super willMoveToWindow:newWindow];
}

- (void)didMoveToWindow{
     NSLog(@"didmovetowindow");
    [super didMoveToWindow];
}

- (void)layoutSubviews
{
    NSLog(@"layoutSubviews");
    [super layoutSubviews];
}


- (void)removeFromSuperview{
    NSLog(@"layoutSubviews");
    [super removeFromSuperview];
}

- (void)dealloc{
    NSLog(@"dealloc");
}

@end
代码语言:javascript复制
- (void)testCase{
    _testView = [TestView new];
    [self.view addSubview:_testView];
    
    [NSTimer scheduledTimerWithTimeInterval:5 repeats:NO block:^(NSTimer * _Nonnull timer) {
        [self removeView];
    }];
}

- (void)removeView{
    [self.testView removeFromSuperview];
    self.testView = nil;
}

打印

代码语言:javascript复制
2019-08-28 11:03:45.370026 0800 TestDemo[28304:5846595] initWithFrame
2019-08-28 11:03:45.370308 0800 TestDemo[28304:5846595] willmovetosuperview
2019-08-28 11:03:45.370479 0800 TestDemo[28304:5846595] didmovetosuperview
2019-08-28 11:03:45.371084 0800 TestDemo[28304:5846595] willmovetowindow
2019-08-28 11:03:45.371413 0800 TestDemo[28304:5846595] didmovetowindow
2019-08-28 11:03:45.374831 0800 TestDemo[28304:5846595] layoutSubviews

移除

代码语言:javascript复制
2019-08-28 11:03:50.372110 0800 TestDemo[28304:5846595] layoutSubviews
2019-08-28 11:03:50.372423 0800 TestDemo[28304:5846595] willmovetosuperview
2019-08-28 11:03:50.372730 0800 TestDemo[28304:5846595] willmovetowindow
2019-08-28 11:03:50.373098 0800 TestDemo[28304:5846595] didmovetowindow
2019-08-28 11:03:50.373302 0800 TestDemo[28304:5846595] didmovetosuperview
2019-08-28 11:03:50.373521 0800 TestDemo[28304:5846595] dealloc

0 人点赞