2012-12-21 43 views
1

我需要一些幫助touchesEnded函數。當屏幕上沒有使用touchesEnded函數的手指時,我想啓動NSTimer。這可能嗎?。目前我有一個touchesBegan函數工作:-)。如何檢測屏幕上沒有手指?

這裏是我的代碼:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    NSUInteger numTaps = [[touches anyObject] tapCount]; 

    if (numTaps >= 2) 
    { 
     self.label.text = [NSString stringWithFormat:@"%d", numTaps]; 
     self.label2.text = @"+1"; 
     [self.button setHidden:YES]; 
    } 
} 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
} 

- (void)showButton 
{ 
    [self.button setHidden:NO]; 
} 
+0

我不明白,你啓動計時器有困難嗎?或者檢測何時不存在觸摸? –

+0

如果問題是'我可以啓動NSTimer嗎?'。當然是。 –

+0

你好0x7fffffff謝謝你的回覆:D。我在檢測屏幕上沒有觸摸時遇到問題: - /我知道如何創建NSTimer,但是如果將它放入touchesEnded函數中,它不會啓動:-( – Aluminum

回答

3

這是棘手。你沒有得到一個事件,告訴你所有的手指都起來了;每個touchesEnded只告訴你這個手指已經起來。所以你必須跟蹤自己的觸摸。通常的技巧是在觸摸到達時將觸摸存儲在可變集中。但是你不能自己存儲觸摸,所以你必須存儲一個標識符。

開始通過戴上UITouch一個類別,以獲得此唯一標識符:

@interface UITouch (additions) 
- (NSString*) uid; 
@end 

@implementation UITouch (additions) 
- (NSString*) uid { 
    return [NSString stringWithFormat: @"%p", self]; 
} 
@end 

現在我們必須保持我們的可變集整個時間,讓我們有接觸,在我們第一次接觸創造它,破壞它的時候我們的最後一滴已經消失了我假設你有一個NSMutableSet實例變量/屬性。下面是僞代碼:

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    // create mutable set if it doesn't exist 
    // then add each touch's uid to the set with addObject: 
    // and then go on and do whatever else you want to do 
} 

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
    // remove uid of *every* touch that has ended from our mutable set 
    // if *all* touches are gone, nilify the set 
    // now you know that all fingers are up 
} 
+0

感謝您的回答,馬特!:-) Mhmm ...空閒計時器會更容易編寫而不是檢測手指嗎? – Aluminum

+0

這不會擴展整個應用程序或由多個視圖控制器組成的接口。 – jrturton

+0

是的,我知道這:-)。空閒計時器會更容易嗎? – Aluminum

2

要創建空閒計時器,最簡單的方法是創建UIApplication的一個自定義子類,並重寫sendEvent: - 在這裏,調用super,然後重新啓動計時器。這將涵蓋所有觸及你的事情。您的應用程序接收到的每一次觸摸都會通過此方法。

要使用自定義應用程序子類,您需要將main.m中的調用修改爲UIApplicationMain(),以插入您的自定義類名稱。

+0

感謝您的回覆,但我不知道如何做到這一點^^「我想我會先嚐試馬特的答案:-) – Aluminum

+0

@jrturton - 這是處理用戶執行長時間的p RESS? – rmaddy

+0

@rmaddy是的,所有的事件。也許如果這是一個長期的新聞,你可能會遇到問題...... – jrturton