iOS UITableView(2)cell注册方式解析

注册cell

是NIB创建的cell用registerNib方法:

dequeue时会调用 cell 的 -(void)awakeFromNib:方法

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

不是NIB创建的cell用registerClass方法:

dequeue时会调用 cell 的-(id)initWithStyle:withReuseableCellIdentifier:方法

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

cell复用

这个方法返回的cell可能为空,所以使用的时候需要判断cell是否为空,若为空则新建一个cell,该方法不需要注册cell!!!

- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier; 
 // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one.

这个方法在iOS6之后才有,获取重用的cell,若无重用的cell,将自动使用所提供的类创建cell并返回,使用该方法需要使用对应的注册cell的方法!!!

- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);
 // newer dequeue method guarantees a cell is returned and resized properly, assuming identifier is registered

这里是例子:

例子一:是NIB创建的cell

  • viewDidLoad方法里的代码:
 [self.mTableView registerNib:[UINib nibWithNibName:@"TestTableViewCell" bundle:nil] forCellReuseIdentifier:kCellIdentifier];
  • cellForRowAtIndexPath方法里的代码:
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];

例子二:不是NIB创建的cell

  • viewDidLoad方法里的代码:
[self.mTableView registerClass:[TestTableViewCell class] forCellReuseIdentifier:kCellIdentifier];
  • cellForRowAtIndexPath方法里的代码:
TestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier forIndexPath:indexPath];

例子三:

  • cellForRowAtIndexPath方法里的代码:
static NSString *cellIdentifier = @"reuseTestTableViewCell";
if (cell == nil)
   {
       cell = [[TestTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
   }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容