在學習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給大家簡單的介紹了一些,希望大家多看看。