UIWindow的妙用(二) 制作App的屏幕保护功能

在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检测屏幕触摸的操作的方法,别的不多说了,直接上代码吧

demo下载地址



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值