【问题标题】:how to stop touchesEnded: withEvent: propogate from subView to ViewController?如何停止 touchesEnded:withEvent:从 subView 传播到 ViewController?
【发布时间】:2017-02-15 09:26:30
【问题描述】:

我有一个视图被添加为 viewController 的子视图。 这个 subview 和 viewController 都实现了这个方法

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

我发现当我点击 subView 时,这两个方法都会被调用。 我只想调用 subview 的touchesEnded。如何很好地实现这一目标? (不要在其中添加手势)

touchesEnded 中,Apple 文档说:“如果您在不调用 super(一种常用模式)的情况下覆盖此方法,那么您还必须覆盖处理触摸事件的其他方法,如果只是作为存根(空)实现。 "

还有什么方法?

【问题讨论】:

    标签: ios uitouch hittest


    【解决方案1】:

    你已经接近了!

    为了防止将触摸事件传递给超级视图,您应该覆盖触摸事件的所有方法。将所有的触摸事件方法添加到您的子视图中,然后您应该就可以了。

    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    }
    
    - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    }
    
    - (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    }
    
    - (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    }
    

    【讨论】:

    • 很好,伙计,它有效!我发现我只需要实现 touchesBegan,它会很好用,谢谢!
    【解决方案2】:

    与其实现子视图的touchesDidEnd,不如在父视图的touchesDidEnd 中完成整个工作

    if([touch anyObject].view == subview){
       return;
    }
    

    这样你就可以知道触摸是来自子视图还是父视图。

    Alternative :你可以在superview和subview中实现这两个方法,但是像上面的代码你可以在superview中返回调用,如果它与之交互的view是subview,并保持在子视图中处理触摸代码

    如果您想要不同的意见,请告诉我们您正在尝试什么,以便我们给出相应的答案

    【讨论】:

    • 事实上,我想将子视图的代码与控制器的代码分开,所以没有办法阻止从子视图到父视图的传递?
    • 如果触摸代码,我认为这是不可能的,因为触摸子视图也会触发超级视图的代码。您所能做的就是像我提到的那样忽略 superview 代码中的触摸,但继续处理触摸 n 子视图中的数据
    • brianLikeApple 给出了一个有趣的答案,我们可以看看,但仍然非常感谢 -_-@souvickcse
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 2011-01-05
    • 1970-01-01
    • 2015-03-28
    • 2012-11-13
    相关资源
    最近更新 更多