Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...