2013-03-29 5 views
0

У меня есть пользовательские ячейки, которые выполняют короткую анимацию при выборе и должны вернуться в свое первое состояние при отмене выбора.UITableView deselectRowAtIndexPath вызывает UITableviewCell setSelected?

Вот мне setSelected

- (void)setSelected:(BOOL)selected animated:(BOOL)animated { 

if (selected && animated) { 
    NSLog(@"animate"); 
    [UIView animateWithDuration:0.3 
          delay:0.0 
         options:UIViewAnimationOptionBeginFromCurrentState 
        animations:^{ 
         self.chevronImage.transform = CGAffineTransformMakeRotation(M_PI); 
         [self.chevronImage setCenter:CGPointMake(self.chevronImage.center.x, self.chevronImage.center.y - 1)]; 
        } 
        completion:nil]; 
} 

if (!selected && animated) { 
    NSLog(@"unanimate"); 
    [UIView animateWithDuration:0.3 
          delay:0.0 
         options:UIViewAnimationOptionBeginFromCurrentState 
        animations:^{ 
         self.chevronImage.transform = CGAffineTransformMakeRotation(0); 
         [self.chevronImage setCenter:CGPointMake(self.chevronImage.center.x, self.chevronImage.center.y + 1)]; 
        } 
        completion:nil]; 
} 

[super setSelected:selected animated:animated]; 
} 

А вот код, который называет его:

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

if (![selectedIndex isEqual:indexPath]) { 
    NSLog(@"select %i", indexPath.row); 
    [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone]; 
} 
if (selectedIndex != nil) { 
    NSLog(@"deselect %i", selectedIndex.row); 
    [tableView deselectRowAtIndexPath:selectedIndex animated:YES]; 
} 
if (controlRowIndex != nil && [indexPath isEqual:controlRowIndex]) { 
    return; 
} 

indexPath = [self modelIndexPathforIndexPath:indexPath]; 
NSIndexPath *indexPathToDelete = controlRowIndex; 

if ([indexPath isEqual:selectedIndex]){ 
    selectedIndex = nil; 
    controlRowIndex = nil; 
} else { 
    selectedIndex = indexPath; 
    controlRowIndex = [NSIndexPath indexPathForRow:indexPath.row + 1 
             inSection:indexPath.section]; 
} 

[self.tableView beginUpdates]; 
if (indexPathToDelete){ 
    [self.tableView deleteRowsAtIndexPaths:@[indexPathToDelete] 
          withRowAnimation:UITableViewRowAnimationFade]; 
} 
if (controlRowIndex){ 
    [self.tableView insertRowsAtIndexPaths:@[controlRowIndex] 
          withRowAnimation:UITableViewRowAnimationFade]; 
} 
[self.tableView endUpdates]; 
} 

Это прекрасно работает, если выбрать строку, а затем нажмите на него еще раз, чтобы отменить выбор. Однако, если я нажимаю на строку 0, а затем нажимаю на строку 1, я получаю обе выбранные строки, строка 0 никогда не будет отменена.

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

EDIT: Добавлен метод полной код

+0

использовать только [тег: Xcode] тег для вопросов о IDE. То же самое для тега [tag: object-c]. Благодаря! – Undo

ответ

0

я ожидал бы, что вы установили в didSelectRowAtIndexPath: переменную selectedIndex, но я не могу увидеть, где вы устанавливаете его. Таким образом, похоже, что вы сравниваете неправильный путь индекса.

Заключительно, я бы сначала сделал отменить выбор.

BOOL tappedSelectedCell = [selectedIndex isEqual:indexPath]; 
if (selectedIndex != nil) { 
    // deselect selectedIndex 
    selectedIndex = nil; 
} 

if (selectedIndex == nil && !tappedSelectedCell) { 
    // select indexPath 
    selectedIndex = indexPath; 
} 

или проще, но немного длиннее

if (selectedIndex == nil) { 
    // select indexPath 
    selectedIndex = indexPath; 
    return; 
} 

if ([selectedIndex isEqual:indexPath]) { 
    // deselect indexPath 
    selectedIndex = nil; 
} 
else { 
    // deselect selectedIndex 
    // select indexPath 
    selectedIndex = indexPath; 
} 
+0

Я действительно установил его там, я просто не опубликовал весь метод, потому что он делает много вещей, которые не применяются к моему вопросу (я вставляю дополнительную строку ниже выбранной). Я отредактирую, чтобы показать весь метод. – hokiewalrus

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