REFrostedViewController与UITableViewCell侧滑删除的坑

RubinRuther 8年前

来自: http://www.rockerhx.com/2015/10/27/2015-10-27-REFrostedViewController-UITableViewCell-Swipe-Delete/

近来项目中需要用到侧滑菜单,测试了一下 REFrostedViewController 还能满足需求,本着不重复造轮子的原则,决定使用。

根据作者: romaonthego 提供的Demo玩起来比较嗨,一看就明白,于是乎我也搞了个 UINavigationController 加入 UIPanGestureRecognizer 手势来实时移动菜单,所有的视图控制器都在这个 UINavigationController 的管理下健康成长。

直到我接到一个需求是表格侧滑删除(也就是Cell的侧滑删除),心想这特么多简单回事,看着这需求,还偷着乐,Android那逼蛋疼了(听说是不好整,具体我也不知道),直接用系统提供的代理三下五除二搞定,那就在这时准备丝滑一下的时候,采坑了。

侧滑删除干死也不响应,善于思考的我淡然是使用排除法,心想UITableView都特么用了多少年了,还能用错了?还是各种检查,发现没问题,无奈还去看了以前的代码,都是妥妥的,用法绝对没错:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {      return YES;  }
</div>
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {      return UITableViewCellEditingStyleDelete;  }
</div>

那现在就怀疑是不是踩到iOS9的坑了,查阅了各种资料和发现也不是这么回事,迫于无奈还是有点怀疑自己,决定新建个空的工程单独写侧滑删除Demo试试,秒秒钟搞定运行,妥妥的,非常丝滑。最后只能检查自己代码了(程序狗出问题了最喜欢先怀疑别人)。

经过一番各种检查,绝逼全都是对的写法,哥怎么肯能出错呢,回望也没在晚上发现下午的代码是一坨坨Shit嘛(PS:看来进步速度太慢了)。最后经过暴力测试,偶尔能在 Cell 上拉出侧滑删除,这一下就上升到手势问题上了,决定从手势开始排查。

果不其然就是自己在 UINavigationController 加的 UIPanGestureRecognizer 这笔影响了侧滑删除手势。两个手势冲突了咋整,直接干啊,还能说啥。。。

吐槽了一大堆,进入正题,其实也没啥好说的,就是使用 UIGestureRecognizerDelegate 的方法解决手势同时存在的问题。

直接上代码:

UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognized:)];  panGesture.delegate = self;  [self.view addGestureRecognizer:panGesture];
</div>
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {            if ([[otherGestureRecognizer.view class] isSubclassOfClass:[UITableView class]]) {          return NO;      }        if( [[otherGestureRecognizer.view class] isSubclassOfClass:[UITableViewCell class]] ||         [NSStringFromClass([otherGestureRecognizer.view class]) isEqualToString:@"UITableViewCellScrollView"] ||         [NSStringFromClass([otherGestureRecognizer.view class]) isEqualToString:@"UITableViewWrapperView"]) {                    return YES;      }      return YES;  }
</div>

解决问题的思路和关键方法就在 gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer: 方法里,我们在捕获到UITableView上的手势的时候就不允许手势的同时存在,在捕获到Cell上的手势时,这样才能侧滑删除,而其他情况下不需要处理,直接返回 YES 以便让 REFrostedViewController 处理手势滑动弹出侧滑菜单。

好了,这里仅填了 REFrostedViewController 和 UITableViewCell 侧滑删除的坑,其他的有小伙伴遇到在一起解决吧。

</div>