我使用以下代码将UIPanGuestureRecognizer添加到整个视图中:
UIPanGestureRecognizer *pgr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
[[self view] addGestureRecognizer:pgr];
在主视图中我有一个UITableView,其中包含此代码以启用滑动删除功能:
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"RUNNING2");
return UITableViewCellEditingStyleDelete;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row >= _firstEditableCell && _firstEditableCell != -1)
NSLog(@"RUNNING1");
return YES;
else
return NO;
}
只有RUNNING1
打印到日志中,并且“删除”按钮不会显示。我相信其原因是UIPanGestureRecognizer,但我不确定。如果这是正确的,我该如何解决这个问题。如果这不正确,请提供原因并解决。谢谢。
来自document:
如果手势识别器识别其手势,则取消视图的剩余触摸。
你的UIPanGestureRecognizer
首先识别滑动手势,所以你的UITableView
不再接受触摸。
要使表格视图与手势识别器同时接收触摸,请将其添加到手势识别器的委托:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
return YES;
}
例如,如果您使用UIPanGuestureRecognizer来显示侧边菜单,那么当您在接受的答案中建议的所有情况下都返回YES时,您可能会看到一些不需要的副作用。例如,当您向上/向下滚动表格视图时打开侧边菜单(带有额外的非常小的左/右方向)或删除按钮在打开侧边菜单时表现异常。您可能想要做的是防止这种副作用是只允许同时水平手势。这将使删除按钮正常工作,但同时滑动菜单时将阻止其他不需要的手势。
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
if ([otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]])
{
UIPanGestureRecognizer *panGesture = (UIPanGestureRecognizer *)otherGestureRecognizer;
CGPoint velocity = [panGesture velocityInView:panGesture.view];
if (ABS(velocity.x) > ABS(velocity.y))
return YES;
}
return NO;
}
或者在Swift中:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
guard let panRecognizer = otherGestureRecognizer as? UIPanGestureRecognizer else {
return false
}
let velocity = panRecognizer.velocity(in: panRecognizer.view)
if (abs(velocity.x) > abs(velocity.y)) {
return true
}
return false
}
如果接受的答案不起作用。尝试添加
panGestureRecognizer.cancelsTouchesInView = false
确保您尚未将手势直接添加到tableview。我在ViewController视图上添加了一个平移手势,可以确认它是否有效。