iPhone開發進階(8)--- 檢測屏幕觸摸事件
這一回來定製 UIView 上的觸摸事件,作爲例子,只是簡單地檢測出觸摸事件並顯示當前座標在控制檯上。
首先添加新文件,如下圖:
在顯示的對話框中選中 Cocoa Touch Class 的 Objective C class ⇒ UIView
在項目的添加菜單中選擇 Touch 。檢測觸摸時間需要實現下面的函數。
1 2 |
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; |
這個函數由用戶觸摸屏幕以後立刻被調到。爲了自定義他的行爲,我們像下面來實現:
1 2 3 4 5 |
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch* touch = [touches anyObject]; CGPoint pt = [touch locationInView:self]; printf("point = %lf,%lf/n", pt.x, pt.y); } |
上面的代碼將觸摸點的座標取出,並打印到控制檯上。
如果需要得到多點觸摸(不只是一根手指)的信息,需要使用 anyObject 實例指定 UIView。
另外,TouchAppDelegate 的 applicationDidFinishLaunching 函數像下面一樣實現:
1 2 3 4 5 6 7 8 |
- (void)applicationDidFinishLaunching:(UIApplication *)application { TouchView* view = [[TouchView alloc] initWithFrame:CGRectMake(100, 100, 200, 200)]; view.backgroundColor = [UIColor greenColor]; [window addSubview:view]; [window makeKeyAndVisible]; [view release]; } |
這裏用 intiWithFrame 指定的矩形區域可以任意。另外爲了明確觸摸的區域大小,設定其 view.backgroundColor。
雖然通過 initWithFrame 在 TouchAppDelegate 內創建了 TouchView 的實例、但是通過 addSubview:view 將管理責任交給了 window 。就是說, TouchAppDelegate 與 window 兩個實例都對 TouchView 實例實施管理。所以這裏用 [view release] 釋放 TouchAppDelegate 的管理責任。