【问题标题】:Forwarding touch events only to the views being touched仅将触摸事件转发到被触摸的视图
【发布时间】:2011-12-02 13:04:59
【问题描述】:

我有一个带有文本字段、按钮和表格的 UIWindow。 我希望能够跟踪屏幕上的所有触摸,然后将它们转发到被触摸的元素。

我已经阅读了关于在Apple documentation 中覆盖sendEvent 但我仍然不明白:

  1. 如何使用hitTest 检索被触摸的元素
  2. 如何向前触摸

这是我目前所拥有的。

- (void) sendEvent:(UIEvent *)event
{

    for (UITouch *touch in [event allTouches])
    {
        /* Get coordinates of touch */
        CGPoint point = [touch locationInView:self];

        /* Get subview being touched */
        /* something like this???
           UIView *receiver = [self hitTest:point withEvent:event];            
         */

        /* Forward touch event to right view */
        /* how??? */

    }

    [super sendEvent:(UIEvent *)event];
}

谢谢。

【问题讨论】:

    标签: ios cocoa-touch hittest touch-event


    【解决方案1】:

    我不确定这是不是最好的解决方案,但我正在关注here 发布的内容。

    基本上我有一个覆盖整个空间的 UIView 子类。此类包含对所有可以触摸的元素的引用。 (我希望有办法避免这种情况)

    这是标题中的代码

     @interface SubclassUIView : UIView {       
        UITextField *text;
        UITableView *table;
        UIButton        *button;
        UIToolbar       *toolbar;
    }
    

    这是实现:

    - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
        CGPoint tableHit = [table convertPoint:point fromView:self];
        CGPoint buttonHit = [button convertPoint:point fromView:self];
        CGPoint toolbarHit = [toolbar convertPoint:point fromView:self];
        CGPoint messageHit = [text convertPoint:point fromView:self];
    
        if ([table pointInside:tViewHit withEvent:event]) return table;
        else if ([button pointInside:buttonHit withEvent:event]) return button;
        else if ([toolbar pointInside:toolbarHit withEvent:event]) return toolbar;
        else if ([text pointInside:messageHit withEvent:event]) return text;
    
        return [super hitTest:point withEvent:event];
    }
    

    【讨论】:

    • 这可行,但触摸永远不会传递到所有内容之上的视图,它们只是被转发。我想知道是否可以“复制”事件并将它们传递给多个视图(在我的例子中,顶视图和被触摸的视图)。
    • 如果你只删除'return'语句会发生什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    相关资源
    最近更新 更多