Vayn
Vayn

Reputation: 2717

How to call touchesBegan in a sub-classed UIView in iOS 8?

I want touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event to be called in a sub-classed UIView.

AppDelegate.m:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    [self.window setRootViewController:[[UIViewController alloc] init]];

    CGRect firstFrame = self.window.bounds;
    HypnosisView *firstView = [[SubClassedView alloc] initWithFrame:firstFrame];

    [self.window addSubview:firstView];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;
}

SubClassedView.h:

#import <UIKit/UIKit.h>

@interface SubClassedView : UIView

@end

SubClassedView.m:

#import "SubClassedView.h"

@implementation SubClassedView

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"Here!");
}

@end

When I touched the screen, the console didn't output "Here!" as I thought it should.

I use the newest Xcode 7 beta 5.

How can I get touchesBegan to be called in the right way?

Thank you very much.

Upvotes: 0

Views: 369

Answers (1)

Stuart
Stuart

Reputation: 37043

You're adding your HypnosisView as the subview of the window, rather than as a subview of the root view controller's view. Your root view controller should be a UIViewController subclass so that you can modify its behaviour to build your app's navigation flow.

Subclass UIViewController, and add your HypnosisView as a subview in its view hierarchy:

@interface MyViewController : UIViewController
@property(nonatomic, strong) HypnosisView *hypnosisView;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.hypnosisView = [[HypnosisView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:hypnosisView];
}

@end

Then in your app delegate, set your view controller subclass to be the root view controller:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    MyViewController *myVC = [[MyViewController alloc] init];
    [self.window setRootViewController:myVC];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    return YES;
}

This is quite an old-school method of doing things though. Is there any reason you're not using storyboards to build your interface?

Upvotes: 2

Related Questions