天天看點

iOS開發筆記之多點觸控(二) 開啟多點觸控的方法

若在真機裝置建構和運作應用程式,就會發現雖然在螢幕上按下了兩根手指,但第二個觸點卻被忽略了。這是因為,預設情況下View是忽略多觸點的,必須專門為需要支援多觸點的View開啟此功能。若要開啟多觸點,需要編寫代碼修改根視圖的multipleToucheEnabled屬性。

self.view.multipleTouchEnabled = TRUE;
           

在觸摸的生命周期裡,每個UITouch對象都為同一個執行個體化對象,也就是說螢幕每個獨立觸摸全程都表示各為同一UITouch對象。在觸摸方法添加代碼如下。

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event //首次在螢幕上檢測到觸摸時調用
{
    NSLog(@"touchesBegan");
    for (UITouch *touch in touches)
    {
        NSLog(@" - %p",touch);
    }
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event //如果觸摸移動到了新的位置則會調用此方法
{
    NSLog(@"touchesMoved");
    for (UITouch *touch in touches)
    {
        NSLog(@" - %p",touch);
    }

}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event//當觸摸離開螢幕調用此方法
{
    NSLog(@"touchesEnded");
    for (UITouch *touch in touches)
    {
        NSLog(@" - %p",touch);
    }

}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event//如系統決定取消此次觸摸,那可能就不調用touchesEnded方法了,在這種情況下會調用touchesCancelled方法
{
    NSLog(@"touchesCancelled");
    for (UITouch *touch in touches)
    {
        NSLog(@" - %p",touch);
    }

}
           

增加一段代碼作用是列印出包含在集合中每個UITouch對象的記憶體位址。下面為裝置螢幕按下兩根手指的輸出結果

2014-01-14 23:52:56.590 bbsTouch[3671:907] touchesBegan

2014-01-14 23:52:56.606 bbsTouch[3671:907]  - 0x1ddaac00

2014-01-14 23:52:56.623 bbsTouch[3671:907] touchesBegan

2014-01-14 23:52:56.628 bbsTouch[3671:907]  - 0x1dd9b690

2014-01-14 23:52:56.633 bbsTouch[3671:907] touchesMoved

2014-01-14 23:52:56.637 bbsTouch[3671:907]  - 0x1ddaac00

2014-01-14 23:52:56.895 bbsTouch[3671:907] touchesMoved

2014-01-14 23:52:56.902 bbsTouch[3671:907]  - 0x1dd9b690

2014-01-14 23:52:56.904 bbsTouch[3671:907]  - 0x1ddaac00

2014-01-14 23:52:56.958 bbsTouch[3671:907] touchesEnded

2014-01-14 23:52:56.963 bbsTouch[3671:907]  - 0x1dd9b690

2014-01-14 23:52:56.967 bbsTouch[3671:907]  - 0x1ddaac00

兩根手指先後觸摸螢幕,進入touchesBegan,記憶體分為0x1ddaac00,0x1dd9b690觸摸過程完成後,記憶體位址也能被系統回收。

轉載請注明原著:http://blog.csdn.net/marvindev

下一篇介紹iOS開發筆記之多點觸控(三) 調用UITouch對象方法——locationInView,多點移動多個對象