如何在iOS 8中的子类UIView中调用touchesBegan?

问题描述:

我想要touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event在子类别UIView中被调用。如何在iOS 8中的子类UIView中调用touchesBegan?

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 

当我触摸屏幕时,控制台没有输出“Here!”因为我认为它应该。

我用的是最新的Xcode 7测试版5.

我怎样才能touchesBegan以正确的方式被称为?

非常感谢。

您正在将HypnosisView作为窗口的子视图添加,而不是作为根视图控制器视图的子视图。您的根视图控制器应该是UIViewController子类,以便您可以修改其行为来构建应用的导航流。

子类UIViewController,并添加您HypnosisView作为其视图层次子视图:

@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 

然后在你的应用程序代理,请将您的视图控制器子类是根视图控制器:

- (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; 
} 

虽然这是相当古老的做法。是否有任何理由不使用故事板来构建界面?

+0

我正在用一本“旧书”(2014年出版)学习iOS开发。我知道这本书有点过时,但我仍然想完成它。谢谢! – Vayn

+1

@Vayn足够公平,学习如何以旧的方式做事情没有任何坏处(注意你2014年不是老了!)。事实上,从长远来看它可能是非常有益的:)。 – Stuart