嵌入UIScrollView的UITableView如何实现左滑删除?

4
我遇到了与UIScrollview enable delete row by swipe相同的问题。
这是一个tableView,它和另一个视图一起作为scrollView的子视图。在我没有将scrollView的scrollEnable属性设置为NO之前,我无法启用“滑动删除”功能,但这会带来另一个问题:我无法在tableView和另一个视图之间滑动。
除了设置scrollEnable属性外,还有其他方法可以启用“滑动删除”吗?
如果没有,那么我应该什么时候将self.scrollEnable = NO设置为什么时候将self.scrollEnable = YES以使“滑动删除”和“在视图之间滑动”都能正常工作?

谢谢

5个回答

6

您需要使用自定义的UIScrollView子类。 它应该与水平滚动视图中的表视图一起使用:

@interface MyCoolScrollView : UIScrollView

@end

@implementation MyCoolScrollView

// Allows inner UITableView swipe-to-delete gesture
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRequireFailureOfGestureRecognizer:(nonnull UIGestureRecognizer *)otherGestureRecognizer
{
    return [otherGestureRecognizer.view.superview isKindOfClass:[UITableView class]];
}

@end

@Peymankh,您还需要将benjaminhallock的答案一起包含在内,才能使其在iOS 11中运行。 - Joe Ginley

5

我已经成功使用过

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer

在一个UIScrollView子类中包含tableview,以便允许驻留在tableview中的UISwipeGestureRecognizer触发,而不会被“主”scrollview的手势识别器吞噬。


3
@THOR的回答还可以,但是如果你的UITableView在UIScrollView中,你可能还有另一个UIView。当你在tableview上向上滑动时,你会意外地滑到“其他视图”上。
这将防止滑动,并允许您进行滑动删除。
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
if (gestureRecognizer.state != 0) {
        return YES;
} else {
    return NO;
}

}


3
如果我没记错的话,触摸事件会被滚动视图消耗掉,而表格的编辑操作没有发生,因为表格没有收到触摸事件。可以通过子类化UIScrollView来解决这个问题,以便将触摸事件传递给下一个响应者。所以,我们只需要重写touchesBegan、moved和ended方法即可。由于我现在在路上,稍后会更新答案并提供所需的代码。祝好!
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.nextResponder touchesBegan:touches withEvent:event];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(!self.dragging)
    {
        [self.nextResponder touchesMoved:touches withEvent:event];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.nextResponder touchesEnded:touches withEvent:event];
}

只需创建一个继承自UIScrollView的类,并在实现中添加以下代码。这将使scrollView不会吞噬触摸事件,而是将其传递下去。当创建scrollView时,请使用刚刚创建的类,而不是UIScrollView。 抱歉耽搁了时间,希望这能有所帮助。 祝好!

0

我知道这个帖子很旧了,但这是Swift 4版本,在iOS 11上为我工作(您将子类化UIScrollView):

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    if (otherGestureRecognizer.view != nil && otherGestureRecognizer.view!.superview != nil) {
        return otherGestureRecognizer.view!.superview!.isKind(of: UITableView.self)
    }

    return false
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    if (gestureRecognizer.state != .possible) {
        return true
    }

    return false
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接