UITableViewCell的两种初始化方式(dequeueReusableCellWithIdentifier):
1,不注册cell的方式:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
if (cell == nil) {
cell =[ [UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"]]; }
return cell;
注意⚠️此方法要对cell进行判断if (cell == nil)。 在iOS6之前都是用这个方法初始化cell。
2,注册的方式:
2.1 注册nib文件:通过xib文件创建的UITableViewCell
需要在tableView ViewDidLoad的时候registerNib
[tableView registerNib:[UINib nibWithNibName:@"CustomCell(cell类名)" bundle:nil] forCellReuseIdentifier:kCellIdentify];
在cellForRowAtIndexPath里就不需要对cell是否为空进行判断
[CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];
2.2 注册代码创建文件:
在tableView ViewDidLoad的时候
[tableView registerClass:[CustomCell(cell类名) class] forCellReuseIdentifier:kCellIdentify];
在cellForRowAtIndexPath里就不需要对cell是否为空进行判断
[CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentify forIndexPath:indexPath];