我有自定义单元格,它们在选择时会执行一个简短的动画,并且在取消选择时应该动画回到它们的第一个状态。
这是我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,所以我有点不知所措。
编辑:添加了完整的方法代码