通过NSNotification从UICollectionView中删除单元格

mel*_*lps 8 ios uicollectionview uicollectionviewcell

我有一个简单的基于UICollectionView的应用程序 - 一个UICollectionView和一个基于NSMutableArray的数据模型,为简单起见.

我可以通过didSelectItemAtIndexPath:delegate方法删除没有问题的单元格:

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self.data removeObjectAtIndex:[indexPath row]];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
}
Run Code Online (Sandbox Code Playgroud)

但是,我正在尝试通过一个子类添加一个删除选项UIMenuController,该UICollectionViewCell子类通过一个UILongPressGestureRecognizer正常触发并且我成功触发一个NSNotification

-(void)delete:(id)sender{
      NSLog(@"Sending deleteme message");
      [[NSNotificationCenter defaultCenter] postNotificationName:@"DeleteMe!" object:self userInfo:nil];
}
Run Code Online (Sandbox Code Playgroud)

我在我的ViewController中捕获它并调用以下方法:

-(void)deleteCell:(NSNotification*)note{
       MyCollectionViewCell *cell = [note object];
       NSIndexPath *path = nil;
       if((path = [self.collectionView indexPathForCell:cell]) != nil){
           [self.data removeObjectAtIndex:[path row]];
           [self.collectionView deleteItemsAtIndexPaths:@[path]];
       }
}
Run Code Online (Sandbox Code Playgroud)

它在deleteItemsAtIndexPaths:call上崩溃了

-[UICollectionViewUpdateItem action]: unrecognized selector sent to instance 0xee7eb10
Run Code Online (Sandbox Code Playgroud)

我已经检查了所有明显的东西 - 比如来自NSNotification的对象和从indexPathForCell:call创建的indexPath,这一切看起来都很好.看起来我正在调用deleteItemsAtIndexPath:在两个地方使用相同的信息,但由于某种原因,它在通过通知路由时失败.

这是错误中给出的地址信息:

(lldb) po 0xee7eb10
(int) $1 = 250080016 <UICollectionViewUpdateItem: 0xee7eb10> index path before update (<NSIndexPath 0x9283a20> 2 indexes [0, 0]) index path after update ((null)) action (delete)
Run Code Online (Sandbox Code Playgroud)

也许更新后的索引路径为空是重要的...

有任何想法吗?

ste*_*ete 25

我发现了一个粗略但有效的解决方法,它甚至会检查在将来的版本中是否已经实施了操作(优于某个类别)

// Fixes the missing action method when the keyboard is visible
#import <objc/runtime.h>
#import <objc/message.h>
__attribute__((constructor)) static void PSPDFFixCollectionViewUpdateItemWhenKeyboardIsDisplayed(void) {
    @autoreleasepool {
    if ([UICollectionViewUpdateItem class] == nil) return; // pre-iOS6.
    if (![UICollectionViewUpdateItem instancesRespondToSelector:@selector(action)]) {
            IMP updateIMP = imp_implementationWithBlock(^(id _self) {});
            Method method = class_getInstanceMethod([UICollectionViewUpdateItem class], @selector(action));
            const char *encoding = method_getTypeEncoding(method);
            if (!class_addMethod([UICollectionViewUpdateItem class], @selector(action), updateIMP, encoding)) {
                NSLog(@"Failed to add action: workaround");
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:添加了iOS5检查.
编辑2:我们在许多商业项目(http://pspdfkit.com)中发布了它,并且效果很好.