美文网首页iOS基础控件学习计划ios
UITableView registerClass与regist

UITableView registerClass与regist

作者: 上发条的树 | 来源:发表于2016-08-11 16:58 被阅读3109次

先看如下两个方法,有何区别呢?

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DataTableViewCell"];

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DataTableViewCell" forIndexPath:indexPath];

可以看出第二个方法多了一个参数。
前者不需要向tableView注册cell的Identifier,但是需要判断返回的cell是否为空,如果为空,需要新建一个cell。如下:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DataTableViewCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DataTableViewCell"];   
    }
    return cell;
}

后者必须向tableView注册cell,可忽略判断获取的cell是否为空,因为无可复用cell时将使用注册时提供的资源去新建一个cell并返回。
注册方法有如下两种:

- (void)registerClass:(nullable Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);

- (void)registerNib:(nullable UINib *)nib forHeaderFooterViewReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);

如果是使用registerClass,还需要在cell的实现文件中重写initWithStyle并加载自己的nib


[self.tableView registerClass:[DataTableViewCell class] forCellReuseIdentifier:@"DataTableViewCell"];

-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle: style reuseIdentifier:reuseIdentifier];
    if (self) {
        NSArray *nibArray = [[NSBundle mainBundle]loadNibNamed:@"DataTableViewCell" owner:nil options:nil];
        self = [nibArray lastObject];
    }
    return self;
}

如果是使用registerNib,则较为简单粗暴,只需要直接调用即可。

[self.tableView registerNib:[UINib nibWithNibName:@"DataTableViewCell" bundle:nil] forCellReuseIdentifier:@"DataTableViewCell"];

插曲

在使用Nib之前,我发现如果使用注册的方式registerClass,那么直接在storyBoard里面关联cell,cell中的控件为nil,所以必须使用nib来自定义cell。
这个问题也有人提到:
http://stackoverflow.com/questions/23365681/tableview-registerclassforcellreuseidentifier-not-work

参考:

相关文章

网友评论

本文标题:UITableView registerClass与regist

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