在IOS的开发中,有的时候出于美观的需要会要求App制作一个屏幕保护的功能,主要就是在App运行时如果经过一段时间没有触摸屏幕,App就会播放屏幕保护的内容,当触摸屏幕的时候,屏幕保护消失,程序继续运行,
首先实现检测到受否有触摸屏幕,那么就要用到UIWindow的实例方法
- (void)sendEvent:(UIEvent *)event 来检测是否触摸屏幕
定义一个UIWindow的子类
#import <UIKit/UIKit.h>
@class MainViewController,ScreenProtectViewController;
@interface ApplicationWindow :
UIWindow
@property (nonatomic,strong)
NSTimer *idleTimer;
@property (nonatomic,strong)
MainViewController *mainVC;
@property (nonatomic,strong)
UINavigationController *naVC;
@property (nonatomic,strong)
ScreenProtectViewController *screenProtectVC;
@end
#import "ApplicationWindow.h"
#import "MainViewController.h"
#import "ScreenProtectViewController.h"
@implementation ApplicationWindow
@synthesize idleTimer,mainVC,screenProtectVC,naVC;
- (id)initWithFrame:(CGRect)frame
{
self = [super
initWithFrame:frame];
if (self) {
// Initialization code
mainVC = [MainViewController
shareInstance];
naVC = [[UINavigationController
alloc] initWithRootViewController:mainVC];
}
return
self;
}
- (void)sendEvent:(UIEvent *)event { //检测屏幕上受否有触摸操作
[super
sendEvent:event];
//
只在开始或结束触摸时 reset 闲置时间,
以减少不必须要的时钟 reset 动作
NSSet *allTouches = [event
allTouches];
if ([allTouches count] >
0) {
// allTouchescount
似乎只会是 1, 因此 anyObject
总是可用的
UITouchPhase phase =((UITouch *)[allTouches
anyObject]).phase;
if (phase ==UITouchPhaseBegan || phase ==
UITouchPhaseEnded)
[self
resetIdleTimer];
}
}
- (void)resetIdleTimer {
if (idleTimer) {
[idleTimer
invalidate];
NSLog(@"NoProtect");
self.rootViewController =naVC; //进入到程序正仓运行的模式
}
idleTimer = [NSTimer
scheduledTimerWithTimeInterval:5
target:self
selector:@selector(idleTimerExceeded)
userInfo:nil
repeats:NO];
//这里可以设置屏幕保护出现的时间间隔
}
- (void)idleTimerExceeded {
NSLog(@"screenProtect");
screenProtectVC = [ScreenProtectViewController
shareInstance];
self.rootViewController =screenProtectVC; //进入到屏幕保护模式
}
@end
实现这个功能主要是运用了UIwiondw的层级关系,还有就是UIwidow检测屏幕触摸的操作的方法,别的不多说了,直接上代码吧