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

來源:互聯網
上載者:User
  • 博主:易飛揚
  • 原文連結 : http://www.yifeiyang.net/iphone-developer-advanced-8-touch-screen-test-event/

    轉載請保留上面文字。

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

    這一回來定製 UIView 上的觸摸事件,作為例子,只是簡單地檢測出觸摸事件並顯示當前座標在控制台上。

    首先添加新檔案,如:

     

     

     

    在顯示的對話方塊中選中 Cocoa Touch Class 的 Objective C class ⇒ UIView

     

     

     

    在項目的添加菜單中選擇 Touch 。檢測觸摸時間需要實現下面的函數。

     

    - (void)touchesBegan NSSet *)touches
    withEvent UIEvent *)event;

     

    這個函數由使用者觸控螢幕幕以後立刻被調到。為了自訂他的行為,我們像下面來實現:

     

    - (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 函數像下面一樣實現:

     

    - (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 的管理責任。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.