Cell注册的两种方式
1.tableView registerNib:(nullable UINib *) forCellReuseIdentifier:(nonnull NSString *)
2.tableView registerClass:(nullable Class) forCellReuseIdentifier:(nonnull NSString *)
Cell注册的形式:
(1)系统cell
1.注册
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
2.不注册
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
(2)自定义cell
1.注册
[self.tableView registerClass:[xxxxCell class] forCellReuseIdentifier:@"cell"];
xxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
2.不注册
xxxxCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell==nil) {
cell=[[xxxxCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
(3)自定义cellXib注册
1.注册
[tableView registerNib:[UINib nibWithNibName:@"xxxxViewCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
xxxxCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
2.不注册
xxxxCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
if (cell == nil) {
cell=[[[NSBundle mainBundle]loadNibNamed:@“xxxxCell" owner:self options:nil]lastObject];
}
(4)storyboard自定义cell
简述:在storyBoard中拖出一个TableViewController,编辑controller上的Cell,可以拖出Imageview和Label,然后建立一个基于UITableViewCell类xxxxViewCell,将StoryBoard上的空间拖对应的属性到xxxxViewCell的.h文件中,同时在StoryBoard中选中TableView—>content设置是动态cell Dynamic Prototypes 还是静态cell Static Cells同时可以设置Cell的rows height,然后选中Cell关联创建的Cell类xxxxViewCell同时设置Identifider 如:cellId
复用:
xxxxViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cellId" forIndexPath:indexPath];
自测版本
在iOS9.3和iOS8.1下测试,只要为tableview注册了相应的cell类,无论用两种方法中的哪一种,都不用手动创建就能获得cell,不会为nil。
然而如果没有为tableview注册cell类,则dequeueReusableCellWithIdentifier:forIndexPath:会crash,crash原因为“must register a nib or a class for the identifier or connect a prototype cell in a storyboard”,即dequeueReusableCellWithIdentifier:forIndexPath:方法必须与register方法配套使用。
但如果没有为tableview注册cell类,dequeueReusableCellWithIdentifier:方法也不会崩溃,只是会返回nil,此时需要我们手动创建cell,如果未创建,则程序会crash,crash原因为“UITableView failed to obtain a cell from its dataSource”,即此时tableView无法获取到cell实例。