美文网首页
touchesBegan:withEvent:方法不被调用

touchesBegan:withEvent:方法不被调用

作者: 瓦西里的椅子 | 来源:发表于2017-10-17 20:17 被阅读0次

在学习iOS编程的时候,遇到自定义UIView的touchesBegan:withEvent:方法不被调用的问题,困在这里很久,直到后来在网上看到一个同样遇到这个问题的人的解决方法才知道问题出在rootViewController上,原始代码如下:

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

    CGRect firstFrame = self.window.bounds;
    BNRHypnosisView *firstView = [[BNRHypnosisView alloc]
                                  initWithFrame:firstFrame];
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window addSubview:firstView];
    [self.window makeKeyAndVisible];
    return YES;
}
Jietu20171017-201036@2x.jpg

根据官方文档对rootViewController的解释,rootViewController会给window设定一个content View,也是UIView类,所以将我自定义的UIView给遮挡了,导致无法触发touchesBegan事件,解决方法是在将自定义UIView添加入window时应该添加在content View上,代码如下

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

    CGRect firstFrame = self.window.bounds;
    BNRHypnosisView *firstView = [[BNRHypnosisView alloc]
                                  initWithFrame:firstFrame];
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window.rootViewController.view addSubview:firstView];
    [self.window makeKeyAndVisible];
    return YES;
}

相关文章

网友评论

      本文标题:touchesBegan:withEvent:方法不被调用

      本文链接:https://www.haomeiwen.com/subject/jbhjuxtx.html