天天看點

iPhone開發進階(8)— 檢測螢幕觸摸事件

4三/10 0

  • 部落客:易飛揚
  • 原文連結 : http://www.yifeiyang.net/iphone-developer-advanced-8-touch-screen-test-event/
  • 轉載請保留上面文字。
  • iPhone開發進階(8)--- 檢測螢幕觸摸事件

    這一回來定制 UIView 上的觸摸事件,作為例子,隻是簡單地檢測出觸摸事件并顯示目前坐标在控制台上。

    首先添加新檔案,如下圖:

    iPhone開發進階(8)— 檢測螢幕觸摸事件
    在顯示的對話框中選中 Cocoa Touch Class 的 Objective C class ⇒ UIView
    iPhone開發進階(8)— 檢測螢幕觸摸事件
    在項目的添加菜單中選擇 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 的管理責任。

繼續閱讀