问题
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:
- How to use
hitTest
to retrieve the element being touched - 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