Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a superview intercept button touch events?

Say I have this code:

#import <UIKit/UIKit.h>

@interface MyView : UIView
@end
@implementation MyView

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    // How can I get this to show up even when the button is touched?
    NSLog(@"%@", [touches anyObject]);
}

@end

@interface TestViewAppDelegate : NSObject <UIApplicationDelegate>
{
    UIWindow *window;
}

@end

@implementation TestViewAppDelegate

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    MyView *view = [[MyView alloc] initWithFrame:[window frame]];
    [view setBackgroundColor:[UIColor whiteColor]];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"Hiya!" forState:UIControlStateNormal];
    [button setFrame:CGRectMake(100.0, 100.0, 200.0, 200.0)];
    [view addSubview:button];

    [window addSubview:view];
    [window makeKeyAndVisible];
}


- (void)dealloc
{
    [window release];
    [super dealloc];
}

@end

Is there any way to intercept the touch events getting sent to the button? What I'd like to eventually do is make a UIView subclass that will tell its view controller (or delegate, whichever) when it detects a swipe so it can "push" the next view controller onto the stack (similar to the iPhone home screen). I figured this was the first step, but I'm open to suggestions if I'm approaching this incorrectly.

like image 337
Michael Avatar asked Aug 15 '09 05:08

Michael


1 Answers

I'd be interested in seeing other solutions, but the easiest way I know of is to override either of these two UIView methods:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;

These methods get called to determine if the touch is within the bounds of the view or any of its subviews, so this is a good point to intercept the touch and then pass it on. Just do what ever you want, and then

return [super hitTest:point withEvent:event];

or

return [super pointInside:point withEvent:event];
like image 142
Felixyz Avatar answered Sep 23 '22 18:09

Felixyz