建立方式彙總,註冊和不註冊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;