UITableViewCell выбранные призраки подпредставления - PullRequest
1 голос
/ 02 апреля 2010

Я узнаю об iPhone SDK и у меня есть интересное исключение с управлением подпредставлением UITableViewCell при нажатии пальцем на несколько строк.

Таблица используется для назначения звуков жестам рук - при нажатии телефона в одном из 3 направлений включается звук для воспроизведения. При выборе строки отображается лист действий с 4 вариантами назначения звука: влево, вниз, вправо и отмена. Звуки могут отображаться в одном, двух или трех направлениях, поэтому любая ячейка может иметь одно из семи состояний: влево, вниз, вправо, влево и вниз, влево и вправо, вниз и вправо или влево вниз и вправо. Если строка сопоставлена ​​с любым из этих семи состояний, соответствующая стрелка или стрелки отображаются в пределах границ строки как подпредставление. Стрелки приходят и уходят, как они должны на данном экране и при прокрутке.

Однако после прокрутки до новой серии строк, только когда я нажимаю пальцем на некоторые (но не все) строки, волшебно появляется стрелка на фоне выбранного состояния. Когда я убираю палец со строки и появляется лист действий, стрелка исчезает. После нажатия любой из четырех кнопок я больше не могу повторить это. Но это действительно сбивает с толку и сбивает с толку, когда эта стрелка вспыхивает на экране, потому что выбранная строка никому не назначена.

Что я не думал, чтобы посмотреть здесь? Весь мой код таблицы вставлен ниже, и это скриншот проблемы: http://www.screencast.com/users/JonathanGCohen/folders/Jing/media/d483fe31-05b5-4c24-ab4d-70de4ff3a0bf

Я неправильно управляю своими подпредставлениями или отсутствует выбранное свойство состояния? Что-то другое? Должен ли я включить больше информации в этот пост, чтобы прояснить ситуацию? Спасибо !!

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row];
    NSString *key = [categories objectAtIndex:section];
    NSArray *nameSection  = [categoriesSounds objectForKey:key];
    static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             SectionsTableIdentifier];
    NSArray *sound = [categoriesSounds objectForKey:key];
    NSString *soundName = [[sound objectAtIndex: row] objectAtIndex: 0];
    NSString *soundOfType = [[sound objectAtIndex: row] objectAtIndex: 1];

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

    cell.textLabel.text = [[nameSection objectAtIndex:row] objectAtIndex: 0];

    NSUInteger soundSection = [[[sound objectAtIndex: row] objectAtIndex: 2] integerValue];
    NSUInteger soundRow = [[[sound objectAtIndex: row] objectAtIndex: 3] integerValue];

        NSUInteger leftRow = [leftOldIndexPath row];
        NSUInteger leftSection = [leftOldIndexPath section];
        if (soundRow == leftRow && soundSection == leftSection && leftOldIndexPath !=nil){
            [selectedSoundLeftAndDown removeFromSuperview];
            [selectedSoundLeftAndRight removeFromSuperview];
            [cell.contentView addSubview: selectedSoundLeft];
            selectedSoundLeft.frame = CGRectMake(200,8,30,30);
        }
        else {
            [cell.contentView sendSubviewToBack: selectedSoundLeft];
        }

        NSUInteger downRow = [downOldIndexPath row];
        NSUInteger downSection = [downOldIndexPath section];
        if (soundRow == downRow && soundSection == downSection && downOldIndexPath !=nil){
            [selectedSoundLeftAndDown removeFromSuperview];
            [selectedSoundDownAndRight removeFromSuperview];
            [cell.contentView addSubview: selectedSoundDown];
            selectedSoundDown.frame = CGRectMake(200,8,30,30);
        }
        else {
            [cell.contentView sendSubviewToBack: selectedSoundDown];
        }

        NSUInteger rightRow = [rightOldIndexPath row];
        NSUInteger rightSection = [rightOldIndexPath section];
        if (soundRow == rightRow && soundSection == rightSection && rightOldIndexPath !=nil){
            [selectedSoundDownAndRight removeFromSuperview];
            [selectedSoundLeftAndRight removeFromSuperview];
            [cell.contentView addSubview: selectedSoundRight];
            selectedSoundRight.frame = CGRectMake(200,8,30,30);
        }
        else {
            [cell.contentView sendSubviewToBack: selectedSoundRight];
        }

        // combos
        if (soundRow == leftRow && soundRow == downRow &&
            soundSection == leftSection && soundSection == downSection){
            [selectedSoundLeft removeFromSuperview];
            [selectedSoundDown removeFromSuperview];
            [selectedSoundLeftAndDownAndRight removeFromSuperview];
            [cell.contentView addSubview: selectedSoundLeftAndDown];
            selectedSoundLeftAndDown.frame = CGRectMake(200,8,30,30);
        }
        else {
            [cell.contentView sendSubviewToBack: selectedSoundLeftAndDown];
        }
        if (soundRow == leftRow && soundRow == rightRow &&
            soundSection == leftSection && soundSection == rightSection){
            [selectedSoundLeft removeFromSuperview];
            [selectedSoundRight removeFromSuperview];
            [selectedSoundLeftAndDownAndRight removeFromSuperview];
            [cell.contentView addSubview: selectedSoundLeftAndRight];
            selectedSoundLeftAndRight.frame = CGRectMake(200,8,30,30);
        }
        else {
            [cell.contentView sendSubviewToBack: selectedSoundLeftAndRight];
        }
        if (soundRow == downRow && soundRow == rightRow &&
            soundSection == downSection && soundSection == rightSection){
            [selectedSoundDown removeFromSuperview];
            [selectedSoundRight removeFromSuperview];
            [selectedSoundLeftAndDownAndRight removeFromSuperview];
            [cell.contentView addSubview: selectedSoundDownAndRight];
            selectedSoundDownAndRight.frame = CGRectMake(200,8,30,30);
        }
        else {
            [cell.contentView sendSubviewToBack: selectedSoundDownAndRight];
        }
        if (soundRow == leftRow && soundRow == downRow && soundRow == rightRow &&
            soundSection == leftSection && soundSection == downSection && soundSection == rightSection){
            [selectedSoundLeftAndDown removeFromSuperview];
            [selectedSoundLeftAndRight removeFromSuperview];
            [selectedSoundDownAndRight removeFromSuperview];
            [selectedSoundLeft removeFromSuperview];
            [selectedSoundDown removeFromSuperview];
            [selectedSoundRight removeFromSuperview];
            [cell.contentView addSubview: selectedSoundLeftAndDownAndRight];
            selectedSoundLeftAndDownAndRight.frame = CGRectMake(200,8,30,30);
        }
        else {
            [cell.contentView sendSubviewToBack: selectedSoundLeftAndDownAndRight];
        }

    [indexPath retain];
    return cell;    
}

Просто хотел поставить обновление на этот пост. Вчера я потратил 12 часов, пытаясь это исправить, и это просто выше моих нынешних навыков. Я установил стиль выбора ячеек на none, что отстой, но сейчас пришло время добавить полотенце.

Я полностью отказался от этого кода в пользу следующего подхода, который проверил все видимые в настоящее время пути индекса на наличие пути индекса, назначенного звуку, а затем удалил подпредставления соответствующим образом:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {


/*  NSArray *allVisibleCells = [table visibleCells];

    leftIsVisible = FALSE;
    downIsVisible = FALSE;
    rightIsVisible = FALSE;

    NSLog(@"\n\n\n", (leftIsVisible ? @"TRUE" : @"FALSE"));

    NSLog(@"Start: %@\n", (leftIsVisible ? @"TRUE" : @"FALSE"));


    for (UITableViewCell *visibleCell in allVisibleCells){

        NSIndexPath *visibleCellIndexPath = [table indexPathForCell: visibleCell];
        NSLog(@"visible cell index path %@\n", visibleCellIndexPath);

        if ([visibleCellIndexPath compare: leftOldIndexPath] == NSOrderedSame) {
            leftIsVisible = TRUE;
            NSLog(@"Compare successful: %@\n", (leftIsVisible ? @"TRUE" : @"FALSE"));
        }
        if ([visibleCellIndexPath compare: downOldIndexPath] == NSOrderedSame) {
            downIsVisible = TRUE;
        }
        if ([visibleCellIndexPath compare: rightOldIndexPath] == NSOrderedSame){
            rightIsVisible = TRUE;
        }
    }

    NSLog(@"After the first fast enumeration: %@\n", (leftIsVisible ? @"TRUE" : @"FALSE"));
    NSLog(@"After check for left is still visible %@\n", (leftIsVisible ? @"TRUE" : @"FALSE"));

    if(leftIsVisible == FALSE){
        [selectedSoundLeft removeFromSuperview];
        [selectedSoundLeftAndDown removeFromSuperview];
        [selectedSoundLeftAndRight removeFromSuperview];
        [selectedSoundLeftAndDownAndRight removeFromSuperview];
    } 
    if(downIsVisible == FALSE){
        [selectedSoundDownAndRight removeFromSuperview];
        [selectedSoundDown removeFromSuperview];
    }
    if (rightIsVisible == FALSE){
        [selectedSoundRight removeFromSuperview];
    }   */

Ответы [ 2 ]

1 голос
/ 02 апреля 2010

У меня нет времени пробираться по 325 строкам кода, но наиболее вероятной причиной вашей проблемы является повторное использование ячеек табличного представления без предварительной очистки их подпредставлений.

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

Каждый раз, когда вы повторно используете ячейку, ваш первый шаг должен состоять в том, чтобы стереть ее до первоначального начального состояния. Только тогда вы должны загрузить новые данные в ячейку.

0 голосов
/ 06 июня 2010

Правильный способ (ну, как говорят Apple Docs) - использовать теги во всех подпредставлениях. Если ячейка создается (не удаляется из очереди / повторно), то вы создаете ячейку как обычно, но устанавливаете уникальный тег (целое число, хотя вы можете использовать определение, чтобы было легче читать). Если ячейка снимается с очереди / используется повторно, вы получаете ячейку, используя теги. Посмотрите в Apple Docs онлайн для настройки UItableViews и есть раздел о настройке ячеек tableview.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...