在学习iOS编程的时候,遇到自定义UIView的touchesBegan:withEvent:方法不被调用的问题,困在这里很久,直到后来在网上看到一个同样遇到这个问题的人的解决方法才知道问题出在rootViewController上。
touchesbegan原始代码如下:
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
self.window=[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];
self.window.rootViewController=[[UIViewControlleralloc]init];
CGRectfirstFrame=self.window.bounds;
BNRHypnosisView*firstView=[[BNRHypnosisViewalloc]
initWithFrame:firstFrame];
self.window.backgroundColor=[UIColorwhiteColor];
[self.windowaddSubview:firstView];
[self.windowmakeKeyAndVisible];
returnYES;
}
touchesbegan代码
根据官方文档对rootViewController的解释,rootViewController会给window设定一个contentView,也是UIView类,所以将我自定义的UIView给遮挡了,导致无法触发touchesBegan事件,解决方法是在将自定义UIView添加入window时应该添加在contentView上,代码如下
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
self.window=[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];
self.window.rootViewController=[[UIViewControlleralloc]init];
CGRectfirstFrame=self.window.bounds;
BNRHypnosisView*firstView=[[BNRHypnosisViewalloc]
initWithFrame:firstFrame];
self.window.backgroundColor=[UIColorwhiteColor];
[self.window.rootViewController.viewaddSubview:firstView];
[self.windowmakeKeyAndVisible];
returnYES;
}
总之,touchesbegan给大家简单的介绍了一些,希望大家多看看。