我开发了一个应用程序,其中一个模块在UIImageView
上有一个self.view
。在imageview
之上,用户可以执行一些正常运行的操作。我的问题是,如果用户未与imageview
进行互动,则必须在5秒后自动从imageview
移除self.view
。我该如何实现呢?我需要使用计时器还是别的什么?
答案 0 :(得分:4)
是的,你可以使用NSTimer
,安排NSTimer
5秒,这样 -
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(removeImageView) userInfo:nil repeats:NO];
此处还有一件事,您需要在用户timer
屏幕时安排此touch
,如果用户touch
再次屏幕,则invalidate
此计时器和{{1}再次。
答案 1 :(得分: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
}