UITableView里Cell的复用详解

在UITableView中Cell的复用方法有两种:dequeueReusableCellWithIdentifier:forIndexPath: 和dequeueReusableCellWithIdentifier:,那么这两个方法有什么区别呢?

一、 dequeueReusableCellWithIdentifier:forIndexPath:是iOS 6之后新出的方法,调用时肯定会返回一个Cell,不必使用Cell的 initWithStyle:reuseIdentifier:进行新建,但使用时必须先进行Cell的注册,否则会报错
reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

Cell的注册方法:
1.代码创建的Cell注册方法:

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

示例:

[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ID"];

2.Xib创建的Cell注册方法:

 - (void)registerNib:(nullable UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);

示例:

[_tableView registerNib:[UINib nibWithNibName:@"XXXCell" bundle:nil] forCellReuseIdentifier:@"XXXCell"];

3.在StoryBoard上创建的Cell系统会自动进行注册,不需要再注册。

二、dequeueReusableCellWithIdentifier:这个方法使用时可以不进行注册,但调用时返回的值有可能会为空,所以需要在cell的tableView:cellForRowAtIndexPath:方法里需要进行判断返回的值是否为空,如果为空需要调用 initWithStyle:reuseIdentifier:方法进行创建

例如:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ID"];
    }
    return  cell;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容