1. 程式人生 > >UITableViewCell初始化的兩種方式 (iOS開發篇)

UITableViewCell初始化的兩種方式 (iOS開發篇)

 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];