Ячейки UITableView странного поведения iPhone

#iphone #ios #uitableview #detailtextlabel

#iPhone #iOS #uitableview #detailtextlabel

Вопрос:

У меня есть представление настроек с 3 разделами. Некоторые ячейки имеют разные стили: Default или Value1. Когда я быстро провожу пальцем вверх или вниз или меняю вид и возвращаюсь назад, текст, который должен быть в ячейке (например, detailTextLabel в моей ячейке со StyleValue1), либо больше не находится здесь, либо иногда в ячейке выше или ниже… Вот скриншоты: на первом изображено нормальное состояние, на втором detailTextLabel из версии переместился в ячейку выше, а на третьем detailTextLabel системы измерения исчез…

Нормальное поведение ячеек
введите описание изображения здесь
введите описание изображения здесь

И вот мой код:

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        if (indexPath.section == 1 amp;amp; indexPath.row == 0) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        }
        else if (indexPath.section == 2 amp;amp; indexPath.row == 2) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
        }
        else {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
    }

    // Selection style.
    cell.selectionStyle = UITableViewCellSelectionStyleGray;

    // Vehicles cells.
    if (indexPath.section == 0 amp;amp; indexPath.row < [self.userCarsArray count]) {
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.textLabel.text = [[NSString stringWithFormat:@"%@ %@ %@", 
                                [[self.userCarsArray objectAtIndex:indexPath.row] year], 
                                [[self.userCarsArray objectAtIndex:indexPath.row] make], 
                                [[self.userCarsArray objectAtIndex:indexPath.row] model]] uppercaseString];

        // Checkmark if current car.
        if ([[EcoAppAppDelegate userCar] idCar] == [[self.userCarsArray objectAtIndex:indexPath.row] idCar]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
            selectedCarPath = indexPath;
        }
        else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }

    // Add car cell.
    if (indexPath.section == 0 amp;amp; indexPath.row == [self.userCarsArray count]) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.textLabel.textColor = [UIColor blackColor];
        cell.textLabel.text = @"Add Vehicle";
    }

    // General cells.
    if (indexPath.section == 1 amp;amp; indexPath.row == 0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"Measurement System";
        cell.textLabel.textColor = [UIColor darkGrayColor];

        if ([EcoAppAppDelegate measurement] == MeasurementTypeMile)
            cell.detailTextLabel.text = @"Miles";
        else
            cell.detailTextLabel.text = @"Meters";
    }

    // Information cells.
    if (indexPath.section == 2 amp;amp; indexPath.row == 0) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"About";
        cell.textLabel.textColor = [UIColor darkGrayColor];
    }
    if (indexPath.section == 2 amp;amp; indexPath.row == 1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.text = @"License";
        cell.textLabel.textColor = [UIColor darkGrayColor];
    }
    if (indexPath.section == 2 amp;amp; indexPath.row == 2) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.text = @"Version";
        cell.textLabel.textColor = [UIColor darkGrayColor];
        cell.detailTextLabel.text = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }

    return cell;
}
  

Вы знаете, как я могу исправить эту проблему? Спасибо!

Ответ №1:

Все ваши ячейки используют один и тот же идентификатор повторного использования, поэтому при прокрутке вы получаете старую ячейку и устанавливаете в ней текст

Вы можете решить свою проблему, установив cell.detailTextLabel.text для всех случаев

При использовании reuseIdentifier вы должны каждый раз устанавливать содержимое всех полей, которое изменяется

Комментарии:

1. Итак, либо я постоянно задаю в своей ячейке все (selectionStyle, detailTextLabel, цвета, accessoryType и т.д.), Либо я могу просто использовать другой идентификатор ячейки для каждой ячейки, верно?

2. Я исправил проблему, установив уникальный идентификатор для каждой ячейки с помощью NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%d%d", indexPath.section, indexPath.row]; Спасибо @someone0!

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

4. Да, у меня просто есть одна проблема, когда я динамически добавляю ячейку в свой первый раздел (когда пользователь создает новый car), происходит сбой, и это потому, что он пытается указать тот же cellIdentifier, который я думаю… Я думаю, мне нужно найти что-то «действительно» уникальное.