2016-10-26 5 views
0

Я храню не более трех предметов, которые разрешено проверять в любое время.Маркировка аксессуаров UITableViewCell не сохраняется при прокрутке после выбора строки

хранить выбранные строки в качестве NSMutabeDictionary называемых selectedRowDictionary в didSelectRowAtIndexPath

Тогда в моем cellForRowAtIndexPath

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

if (_selectedRowDictionary && [_selectedRowDictionary count]) { 
    for (NSString *rowSelected in _selectedRowDictionary) { 
     BOOL isRowSelected = [[_selectedRowDictionary valueForKey:rowSelected] integerValue]; 
     if (isRowSelected){ 
      NSLog(@"rowSelected: %@", rowSelected); 
     } else { 
      NSLog(@"rowNotSelected: %@", rowSelected); 
     } 

     int rowIndexSelected = [[rowSelected substringFromIndex:[rowSelected length] - 1 ] integerValue]; 

     if (isRowSelected && rowIndexSelected == indexPath.row) { 
      cell.accessoryType = UITableViewCellAccessoryCheckmark; 
     } else { 
      cell.accessoryType = UITableViewCellAccessoryNone; 
     } 
    } 
}  
return cell; 
} 

- - didSelectRowAtIndexPath:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 


if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { 
    cell.accessoryType = UITableViewCellAccessoryNone; 

    if (_selectedRowDictionary) { 
     [_selectedRowDictionary removeObjectForKey:[NSString stringWithFormat:@"row%d", indexPath.row]]; 
     NSLog(@"row %d removed from array", indexPath.row); 
    } 

} else { 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    [_selectedRowDictionary setValue:[NSNumber numberWithBool:YES] forKey:[NSString stringWithFormat:@"row%d", indexPath.row]]; 
} 

if ([_selectedRowDictionary count] > 3) { 
    UITableViewCell *lastSelectedCell = [tableView cellForRowAtIndexPath:indexPath]; 
    lastSelectedCell.accessoryType = UITableViewCellAccessoryNone; 

    [_selectedRowDictionary removeObjectForKey:[NSString stringWithFormat:@"row%d", indexPath.row]]; 
    NSLog(@"row selected > 3, row%d not selected", indexPath.row); 
} 
} 

Могу ли я что-то отсутствует, что вызывает ячейку, которую нужно отменить, когда я прокручиваю вниз он настольный?

Когда я NSLog словаря, он говорит, что эти строки существуют, и были выбраны

Я проверил подобные вопросы, но я думал, что решается вопрос утилизации клеток уже.

ответ

1

Вы можете вместо этого использовать изменчивый массив?

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifer" forIndexPath:indexPath]; 

    if ([_selectedRowArray containsObject:indexPath]) 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    else 
     cell.accessoryType = UITableViewCellAccessoryNone; 

    return cell; 
} 


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    if ([_selectedRowArray containsObject:indexPath]) { 
     [_selectedRowArray removeObject:indexPath]; 
    } else { 
     if (_selectedRowArray.count < 3) 
      [_selectedRowArray addObject:indexPath]; 
     else { 
      // Don't select it 
     } 
    } 

    [tableView reloadData]; 
} 
+0

Я получаю 'Нет видимого интерфейса для 'NSMutableArray' объявляет селектор removeObjectIndexPath'? Вы имели в виду 'removeObjectAtIndex: indexPath.row'? – Simon

+0

Я пропустил двоеточие. Обновил мой ответ. – norders

+0

Спасибо! Это фиксировало это (: знаете ли вы, что было не так с моей предыдущей попыткой? – Simon

1

Я редактирую ваш код, попробуйте этот код. изменения

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifer" forIndexPath:indexPath]; 
    BOOL isRowSelected = [[_selectedRowDictionary valueForKey:@(indexPath.row)] boolValue] 
    if (isRowSelected) { 
     cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    } else { 
     cell.accessoryType = UITableViewCellAccessoryNone; 
    } 
    return cell; 
} 

Код в - didSelectRowAtIndexPath

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 


if (cell.accessoryType == UITableViewCellAccessoryCheckmark) { 
    cell.accessoryType = UITableViewCellAccessoryNone; 

    if (_selectedRowDictionary) { 
     [_selectedRowDictionary removeObjectForKey:@(indexPath.row)]; 
     NSLog(@"row %d removed from array", indexPath.row); 
    } 

} else { 
    if (_selectedRowDictionary.count == 3) { 
     // Don't allow for Selection 
     return; 
    } 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
    [_selectedRowDictionary setValue:@(YES) forKey:@(indexPath.row)]; 
    } 
} 

Пользователь должен отменить предыдущую выбранную строку, чтобы выбрать новую строку. Я редактировал ваш код оптимизированным образом, я надеюсь, что этот код работает для вас.

Смежные вопросы