views:

4388

answers:

2

Hi,

I created a very very basic iPhone app with File/New Projet/View-Based application. No NIB file there.

Here is my appDelegate

.h

    @interface MyAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    MyViewController *viewController;
}

.m

    - (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after app launch    
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];
}

And here is my loadView method in my controller

 - (void)loadView {
 CGRect mainFrame = [[UIScreen mainScreen] applicationFrame];
 UIView *contentView = [[UIView alloc] initWithFrame:mainFrame];
 contentView.backgroundColor = [UIColor redColor];
 self.view = contentView;
 [contentView release];
}

Now, in order to catch the touchesBegan event, I created a new subclass of UIView:

.h

@interface TouchView : UIView {
}

.m

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
 NSLog(@"Touch detected");

}

and modified the second line in my loadView into this :

 TouchView *contentView = [[UIView alloc] initWithFrame:mainFrame];

Why is touchesBegan never called?

A: 

Found the solution : touchesBegan gets called on the viewController, not on the view...

Very close. Apparently, the UIViewController gets the touchesBegan/touchesEnded/etc messages *before* the UIView. The UIViewController doesn't pass the message along to the UIView (by calling [super touchesBegan]) by default. So you need to move or forward to the touches* functions *if* your UIView has a controller. Its confusing and never been documented properly but this is traditional the cocoa way.
Dave
+1  A: 

If you change the loadView into this:

TouchView *contentView = [[TouchView alloc] initWithFrame:mainFrame];

You should have no problem catching the touches in TouchView. In your code, you didn't create a TouchView instance, you created a UIView instance.

George Zhu