2012-05-28 18 views
3

的5秒鐘後自動刪除的ImageView我已經開發,具有在self.view一個UIImageView一個模塊的應用程序。在那段imageview,用戶可以做的工作正常一些操作。我的問題是,如果用戶不與imageview交互那麼imageview將不得不從self.view 5秒鐘後自動刪除。我怎樣才能實現這個?我是否需要使用計時器或其他東西?無活動

回答

4

是的,你可以使用NSTimer爲,安排這樣的NSTimer 5秒 -

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(removeImageView) userInfo:nil repeats:NO]; 

這裏還有一件事,你需要安排此timer當用戶touch屏幕,如果用戶touch屏幕再然後invalidate這個計時器和reschedule一次。

+0

你忘了「,如果用戶不與交互圖像視圖」的一部分.... – lnafziger

+1

對不起,我真的錯過了......我更新我的答案 – saadnib

3

我子類的UIWindow和我CustomWindow類實現的代碼(我的時間爲3分鐘無activiy的則定時器「火災」)

@implementation CustomWindow 

// Extend method 
- (void)sendEvent:(UIEvent *)event 
{ 
    [super sendEvent:event]; 

    // Only want to reset the timer on a Began touch, to reduce the number of timer resets. 
    NSSet *allTouches = [event allTouches]; 
    if ([allTouches count] > 0) 
    { 
     // allTouches count only ever seems to be 1, so anyObject works here. 
     UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase; 
     if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded) 
     { 
      // spirko_log(@"touch and class of touch - %@", [((UITouch *)[allTouches anyObject]).view class]); 
      [self resetIdleTimer:NO]; 
     } 
    } 
} 


- (void) resetIdleTimer:(BOOL)force 
{ 
    // Don't bother resetting timer unless it's been at least 5 seconds since the last reset. 
    // But we need to force a reset if the maxIdleTime value has been changed. 
    NSTimeInterval now = [NSDate timeIntervalSinceReferenceDate]; 
    if (force || (now - lastTimerReset) > 5.0) 
    { 
     // DebugLog(@"Reset idle timeout with value %f.", maxIdleTime); 
     lastTimerReset = now; 
     // Assume any time value less than one second is zero which means disable the timer. 
     // Handle values > one second. 
     if (maxIdleTime > 1.0) 
     { 
      // If no timer yet, create one 
      if (idleTimer == nil) 
      { 
       // Create a new timer and retain it. 
       idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimeExceeded) userInfo:nil repeats:NO] retain]; 
      } 
      // Otherwise reset the existing timer's "fire date". 
      else 
      { 
       // idleTimer = [[NSTimer scheduledTimerWithTimeInterval:maxIdleTime target:self selector:@selector(idleTimeExceeded) userInfo:nil repeats:NO] retain]; 

       [idleTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:maxIdleTime]]; 
      } 
     } 
     // If maxIdleTime is zero (or < 1 second), disable any active timer. 
     else { 
      if (idleTimer) 
      { 
       [idleTimer invalidate]; 
       [idleTimer release]; 
       idleTimer = nil; 
      } 
     } 
    } 
} 

- (void) idleTimeExceeded 
{ 
    // hide your imageView or do whatever 
} 
+0

這將需要5秒一些變化(如果少於5秒,你不啓動新的計時器,並停止還剩1秒),但是正確的做法。 – lnafziger