Подтвердить что ты не робот

Стиль UITableViewCell и dequeueReusableCellWithIdentifier

Итак, я зарегистрирую свою ячейку:

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    // setting up the cell
}

Проблема заключается в том, что я не могу установить свойство cell.detailTextLabel.text. Ячейка никогда не nil.

4b9b3361

Ответ 1

При первом вызове табличный вид registerClass приведет к тому, что t21 будет возвращать не-nil-ячейку, если идентификатор повторного использования ячейки соответствует.

Я считаю, что registerClass обычно используется для ячеек, которые будут пользовательской ячейкой, полученной из UITableViewCell. Ваша пользовательская ячейка может перезаписать initWithStyle и установить там стиль.

Не всегда необходимо создать пользовательскую ячейку.

Если вы хотите установить стиль ячейки, не вызывайте registerClass.

Ответ 2

вам нужно выполнить 3 изменения для достижения цели:

  • удалить инструкцию registerClass.
  • UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier forIndexPath: indexPath]; = > UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: CellIdentifier];
  • Использовать initWithStyle: UITableViewCellStyleSubtitle

обычно есть два способа создать ячейку с утилью, во-первых, с пользовательским UITableViewCell, установить стиль в init. во-вторых, с последующим кодом, который вы хотели:

static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}

Ответ 3

Вам нужно изменить стиль ячейки:

if (cell == nil) {
                    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

к этому

if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }

Это будет работать для вас.

Ответ 4

Попробуйте использовать стиль UITableViewCellStyleSubtitle для ячейки. Измените строку в инструкции if:

cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

Ответ 5

Самый простой способ - использовать раскадровку и установить стиль ячейки в IB. В этом случае вы ничего не должны регистрировать, а также не должны иметь предложение if (cell == nil). Кажется, не имеет значения, используете ли вы dequeueReusableCellWithIdentifier: или dequeueReusableCellWithIdentifier: forIndexPath. Они оба гарантированно возвратят ячейку, когда эта ячейка создана в раскадровке.

Ответ 6

Это старый вопрос. Я просто хочу предложить альтернативное решение.

Почему бы не попробовать ниже, после регистрации ячейки:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

то do:

[cell initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier ];

Это работает для меня.

Ответ 7

Создайте пользовательскую ячейку. Измените его стиль в построителе интерфейса. Использовать табличный вид зарегистрировать ячейку из nib вашего контроллера представления.

Set the style

И код:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.tableView registerNib:[UINib nibWithNibName:@"YourCustomCell" bundle:nil] forCellReuseIdentifier:kReuseIdentifier];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YourCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseIdentifier];

    // Do things with the cell. 
    // The cell has no chance to be nil because you've already registered it in viewDidLoad method. 
    // So there not need to write any code like if(cell==nil).
    // Just use it.

    return cell;
}