搜索
您的当前位置:首页正文

initWithCoder & initWithFram

来源:二三娱乐

今天一同事在看一代码片段的时候问我,为什么此处需要同时对initWithCoder 和 initWithFrame 进行初始化,我想了想这应该是为了同时兼顾从文件和从代码解析的对象初始化吧,然而发现自己对这几个概念还是不太清晰,特此笔记下。

- (instancetype)initWithCoder:(NSCoder *)aDecoder ;
- (void)awakeFromNib;
- (instancetype)initWithFrame:(CGRect)frame;
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;

一、initWithCoder & initWithFrame

  • initWithCoder:使用文件加载的对象调用(如从xib或stroyboard中创建)
  • initWithFrame:使用代码加载的对象调用(使用纯代码创建)

二、awakeFromNib & initWithCoder

  • initWithCoder: 只要对象是从文件解析来的,就会调用initWithCoder
  • awakeFromNib: 从xib或者storyboard加载完毕就会调用

顺序是: initWithCoder ===> awakeFromNib

三、initWithFrame & initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier

  • 此处是针对于UICollectionView 和 UITableView 自定义 Cell 的时候需要小注意下,UITableViewCell 是后者,而 UICollectionViewCell 是前者。
Top