美文网首页
UITableViewCell 注册的含义

UITableViewCell 注册的含义

作者: 栖息于旷野 | 来源:发表于2019-04-17 22:25 被阅读0次

结论:

所谓的注册不注册其实指:【有没有为某一identifier 注册一个Class】

或者理解为:有没有把一个identifier和一个Class相互绑定。

如果发生绑定,当标识符为identifier 的Cell队列中没有可复用的cell时,系统会自动创建一个绑定的Class类型的cell。

如果没有绑定Class,那么我们要手动判定是否无可复用的cell,并手动新建一个cell。

一句话总结:注册后就不用管cell是否需要新建了。

注册情况:

当使用register方法

//不使用nib- (void)registerClass:(nullableClass)cellClass forCellReuseIdentifier:(NSString*)identifier;//使用nib- (void)registerNib:(nullableUINib*)nib forCellReuseIdentifier:(NSString*)identifier;

cellClass和identifier相互绑定,对应使用dequeue方法(有indexPath参数)

//使不使用nib对于dequeue无影响- (__kindofUITableViewCell*)dequeueReusableCellWithIdentifier:(NSString*)identifier forIndexPath:(NSIndexPath*)indexPath;

这时候不需要判断cell是否为空,判断和创建步骤交由系统来自动执行。

注1:注册的情况下cell默认调用如下两个方法实现实例化

//不使用nib-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier;//使用nib- (void)awakeFromNib;

系统默认且仅会调用这两个固定的方法来实现实例化。

所以若需要自定义,重写这两个方法。

若需要传参则需要单独设立方法,在dequeue方法之后调用。

注2:一个class可以绑定多个identifier。

不注册情况:

而不使用register方法,没有把Class和identifier绑定,所以常见的写法是这样的

UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];if(cell ==nil) {    cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@"cell"];}

我们直接使用dequeue方法(无indexPath参数),然后手动判断是否取到可复用的cell。如果没有取到,我们手动的去实例化一个新的cell。

注:

不注册的劣势在于我们需要手动判断和手动实现实例化

但优势在于,实例化的方法可以完全自定义,我们可以在实例化时就把参数传入。

基础示例:

1.基于class的注册,使用registerClass方法

//在viewDidLoad 中使用[self.tableView registerClass:[UITableViewCellclass] forCellReuseIdentifier:@"identifier"];//在tableView: cellForRowAtIndexPath: 中使用UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"forIndexPath:indexPath];

2.基于nib的注册,使用registerNib方法

//在viewDidLoad 中使用[self.tableView registerNib:[UINibnibWithNibName:@"MyCommonCell"bundle:nil] forCellReuseIdentifier:@"identifier"];//在tableView: cellForRowAtIndexPath: 中使用UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"forIndexPath:indexPath];

3.基于class的不注册,手动判别cell是否为空

//在tableView: cellForRowAtIndexPath: 中使用UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];if(cell ==nil) {    cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:@"cell"];}

4.基于class的不注册,手动判别cell是否为空

//在tableView: cellForRowAtIndexPath: 中使用UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];if(cell ==nil) {    cell = [[[NSBundlemainBundle]loadNibNamed:@"MyCommonCell"owner:selfoptions:nil] lastObject];}

注:基于nib的创建也是不能夹带参数的,实例化后单独使用传参方法。

作者:Mi欧阳

链接:https://www.jianshu.com/p/7645aabeae57

来源:简书

简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

相关文章

网友评论

      本文标题:UITableViewCell 注册的含义

      本文链接:https://www.haomeiwen.com/subject/myzowqtx.html