Cell的複用機制問題總結

建立方式彙總,註冊和不註冊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; // Used by the delegate to acquire an already allocated cell, in lieu of allocating a new one. (返回給代理一個已經分配的cell,代替一個新的cell,若是沒有已分配的cell,則返回nil,使用這個方法就不須要註冊了) - (__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 若是cell的identifier是註冊過的,那麼這個新列出的方法保證返回一個cell (有分配的就返回已分配的cell,沒有返回新的cell)並適當調整大小,可省略cell空值判斷步驟,用這個方法cell必須註冊,不是自定義的cell,UITableViewCell也要註冊
相關文章
相關標籤/搜索