建立方式汇总,注册和不注册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];
}
复用机制很少作赘述,只讲解一下注册的复用机制
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier: identifier] ;
这个方法的做用是,当咱们从重用队列中取cell的时候,若是没有,系统会帮咱们建立咱们给定类型的cell,若是有,则直接重用. 这种方式cell的样式为系统默认样式.在设置cell的方法中只须要:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// 重用队列中取单元格 因为上面已经注册过单元格,系统会帮咱们作判断,不用再次手动判断单元格是否存在
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: identifier forIndexPath:indexPath] ;
return cell ;
}
注册和不注册的区别:
- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;