Я знаю, что есть похожие вопросы, но утвержденные ответы, похоже, не работают для меня. Итак, мой сценарий - у меня есть UITableView
, и я хочу добавлять и удалять элементы, сканируя штрих-код. Все это прекрасно работает, за исключением того, что я не могу получить UITableView
для отображения обновленной информации. Проблема, в частности, связана с методом tableView:cellForRowAtIndexPath:
при каждой перезагрузке после начальной. Точнее говоря, ячейка всегда , а не nil
, поэтому она пропускает новую логику создания ячейки.
Для других вопросов, таких как мой, ответ таков: проблема заключается в идентификаторе ячейки. Ну, я попытался возиться с этим, и это не сработало. Вот мой код:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
if (indexPath.section < vehicle.inventoryCategoriesCount) {
cell = [tableView dequeueReusableCellWithIdentifier:@"ModelCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"ModelCell"] autorelease];
NSString *model = [[[vehicle.inventory filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"category == %@", [vehicle.inventoryCategories objectAtIndex:indexPath.section]]] valueForKeyPath:@"@distinctUnionOfObjects.model"] objectAtIndex:indexPath.row];
cell.textLabel.text = model;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", [[vehicle.inventory filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"model == %@", model]] count]];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
} else {
cell = [tableView dequeueReusableCellWithIdentifier:@"RemoveCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RemoveCell"] autorelease];
cell.textLabel.text = @"Remove an Item";
cell.textLabel.textColor = [UIColor redColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
return cell;
}
Итак, в этом примере кода у меня есть два разных идентификатора ячейки для отдельных разделов. Это ModelCell и RemoveCell . Ну, они не работают как решение, потому что ничего не происходит. Если я изменяю идентификатор ячейки при выделении новой ячейки, она работает, потому что она просто стирает все, поскольку идентификаторы не совпадают, но я собираюсь предположить, что это неправильно и что для этого должно быть лучшее решение. или я просто что-то не так делаю.
Буду признателен за помощь в этом. Я потратил целый день на этот кусок кода, и я нигде не получил, и я хотел бы исправить это и перейти к другой части моего приложения ...
Заранее спасибо за любую помощь!
UPDATE
Благодаря @fluchtpunkt проблема была решена. Для всех, кто может столкнуться с этим в будущем, вот исправленный код. Я решил сделать идентификатор еще более уникальным, добавив к нему номер раздела.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
if (indexPath.section < vehicle.inventoryCategoriesCount) {
NSString *identifier = [NSString stringWithFormat:@"ModelCell-%d", indexPath.section];
cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSString *model = [[[vehicle.inventory filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"category == %@", [vehicle.inventoryCategories objectAtIndex:indexPath.section]]] valueForKeyPath:@"@distinctUnionOfObjects.model"] objectAtIndex:indexPath.row];
cell.textLabel.text = model;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", [[vehicle.inventory filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"model == %@", model]] count]];
} else {
cell = [tableView dequeueReusableCellWithIdentifier:@"RemoveCell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RemoveCell"] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.textColor = [UIColor redColor];
}
cell.textLabel.text = @"Remove an Item";
}
return cell;
}
UPDATE
Окончательная версия кода, которая исправляет мое недопонимание того, как работает идентификатор. Я решил, что буду держать это просто, поэтому я назвал идентификаторы в честь типа стиля ячейки.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
if (indexPath.section < vehicle.inventoryCategoriesCount) {
cell = [tableView dequeueReusableCellWithIdentifier:@"Value1"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Value1"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSString *model = [[[vehicle.inventory filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"category == %@", [vehicle.inventoryCategories objectAtIndex:indexPath.section]]] valueForKeyPath:@"@distinctUnionOfObjects.model"] objectAtIndex:indexPath.row];
cell.textLabel.text = model;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%d", [[vehicle.inventory filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"model == %@", model]] count]];
} else {
cell = [tableView dequeueReusableCellWithIdentifier:@"Default"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Default"] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.textColor = [UIColor redColor];
}
cell.textLabel.text = @"Remove an Item";
}
return cell;
}