Wonderful use of UIWindow (2) screen protection function of the App, uiwindowapp
In IOS development, sometimes the App is required to create a screen protection function out of aesthetic needs. If the App does not touch the screen after a period of time, the App will play the screen-protected content. When you touch the screen, the screen-protected content disappears and the program continues to run,
First, to detect whether a touch screen is available, you need to use the instance method of UIWindow.
-(Void) sendEvent :( UIEvent *) event to detect whether to touch the screen
Define a subclass of A 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 = [superinitWithFrame: frame];
If (self ){
// Initialization code
MainVC = [mainviewcontrollerw.instance];
NaVC = [[UINavigationControlleralloc] initWithRootViewController: mainVC];
}
Return self;
}
-(Void) sendEvent :( UIEvent *) event {// detect whether a touch operation is performed on the screen
[SupersendEvent: event];
// Only reset idle time at the start or end of touch to reduce unnecessary clock reset actions
NSSet * allTouches = [event allTouches];
If ([allTouches count]> 0 ){
// AllTouchescount seems to be only 1, so anyObject is always available
UITouchPhase phase = (UITouch *) [allTouchesanyObject]). phase;
If (phase = UITouchPhaseBegan | phase = UITouchPhaseEnded)
[SelfresetIdleTimer];
}
}
-(Void) resetIdleTimer {
If (idleTimer ){
[IdleTimerinvalidate];
NSLog (@ "NoProtect ");
Self. rootViewController = naVC; // enter the running mode of the program main warehouse.
}
IdleTimer = [NSTimerscheduledTimerWithTimeInterval: 5 target: selfselector: @ selector (idleTimerExceeded) userInfo: nilrepeats: NO];
// You can set the interval at which Screen Protection appears.
}
-(Void) idleTimerExceeded {
NSLog (@ "screenProtect ");
ScreenProtectVC = [screenprotectviewcontroller1_instance];
Self. rootViewController = screenProtectVC; // enters the screen protection mode.
}
@ End
This function is mainly implemented by using the hierarchical relationship of UIwiondw, as well as the method for detecting screen touch operations by UIwidow. If you don't want to talk about anything else, simply go to the code.
Demo