时间:2020-12-09 20:13:02 | 栏目:iOS代码 | 点击:次
前言
iOS开发中,创建View常见的两种方式一个是纯代码,一个是借助于XIB;创建ViewController常见的也有两种方式一个是纯代码,一个是借助于StoryBoard。
通过交流我发现很多童鞋对这些概念都很模糊,于是通过实验写一篇博客供参考。
重写View的如下方法
@implementation YFView -(instancetype)init{ self = [super init]; NSLog(@"%s", __func__); return self; } -(instancetype)initWithFrame:(CGRect)frame{ self = [super initWithFrame:(CGRect)frame]; NSLog(@"%s", __func__); return self; } -(instancetype)initWithCoder:(NSCoder *)aDecoder{ self = [super initWithCoder:aDecoder]; NSLog(@"%s", __func__); return self; } -(void)awakeFromNib{ [super awakeFromNib]; NSLog(@"%s", __func__); } -(void)layoutSubviews{ NSLog(@"%s", __func__); } @end
重写ViewController的如下方法
@implementation YFViewController -(void)loadView{ NSLog(@"%s", __func__); [super loadView]; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. NSLog(@"%s", __func__); self.view.backgroundColor = [UIColor redColor]; } -(void)viewDidAppear:(BOOL)animated{ NSLog(@"%s", __func__); [super viewDidAppear:animated]; } -(instancetype)init{ self = [super init]; NSLog(@"%s", __func__); return self; } -(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ self = [super initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil]; NSLog(@"%s", __func__); return self; } -(instancetype)initWithCoder:(NSCoder *)aDecoder{ self = [super initWithCoder:aDecoder]; NSLog(@"%s", __func__); return self; } -(void)awakeFromNib{ NSLog(@"%s", __func__); [super awakeFromNib]; } @end
结论总结
如果控制器是直接通过代码创建出来的,并且调用方法为[[YFViewController alloc]init]
创建VC的生命周期为:
-[YFViewController initWithNibName:bundle:] -[YFViewController init] -[YFViewController loadView] -[YFViewController viewDidLoad] -[YFViewController viewDidAppear:]
如果创建控制器时勾选了XIB,那么调用方法为[[YFViewController alloc]init]
创建VC时的生命周期为:
-[YFViewController initWithNibName:bundle:] -[YFViewController init] -[YFViewController loadView] -[YFViewController viewDidLoad] -[YFViewController viewDidAppear:]
如果是通过SB创建控制器,那么VC的生命周期为:
-[ViewController initWithCoder:] -[ViewController awakeFromNib] -[ViewController loadView] -[ViewController viewDidLoad] -[ViewController viewDidAppear:]
如果纯代码创建UIView,调用方式为YFView *yfView = [[YFView alloc]init];
那么它的生命周期为:
-[YFView initWithFrame:] -[YFView init] -[YFView layoutSubviews]
如果纯代码创建UIView,调用方式为YFView *yfView = [[YFView alloc]initWithFrame:[UIScreen mainScreen].bounds];
那么它的生命周期为:
-[YFView initWithFrame:] -[YFView layoutSubviews]
如果通过XIB创建UIView,调用方式为NSArray *array = [[NSBundle mainBundle]loadNibNamed:@"YFView" owner:nil options:nil];[array lastObject];
那么它的生命周期为:
-[YFView initWithCoder:] -[YFView awakeFromNib] -[YFView layoutSubviews]
总结