在学习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;
}
网友评论