Forwarding touch events only to the views being touched

混江龙づ霸主 提交于 2019-12-23 05:20:26

问题


I have a UIWindow with a text field, a button, and a table. I would like to be able to track all the touches on the screen and then forward them to the element being touched.

I have read about overriding sendEvent in the Apple documentation but I still do not understand:

  1. How to use hitTest to retrieve the element being touched
  2. How to forward touches

This is what I have so far.

- (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];
}

Thank you.


回答1:


I am not sure this is the best solution but I am following what has been posted here.

Basically I have a subclass of UIView covering the entire space. Such class contains a reference to ALL the elements that can be touched. (I wish there was a way to avoid that)

This is the code in the header

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

And this is the implementation:

- (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];
}


来源:https://stackoverflow.com/questions/8356723/forwarding-touch-events-only-to-the-views-being-touched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!