3

我开发了一个应用程序,其中一个模块上有UIImageView一个self.view. 在此之上imageview,用户可以执行一些运行良好的操作。我的问题是,如果用户没有与之交互,imageview那么imageview必须self.view在 5 秒后自动删除。我该如何实施?我需要使用计时器或其他东西吗?

4

2 回答 2

4

是的,您可以使用NSTimer它,NSTimer像这样安排 5 秒 -

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

这里还有一件事,您需要timer在用户touch使用屏幕时安排此操作,如果再次使用touch屏幕,则再次使用invalidate此计时器reschedule

于 2012-05-28T04:30:54.910 回答
3

我将 UIWindow 子类化并在我的 CustomWindow 类中实现了代码(我的时间是 3 分钟的非活动时间,然后计时器“触发”)

@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
}
于 2012-05-28T05:11:41.660 回答