先看下效果圖(布局就隨便看看吧 ,重點(diǎn)是效果??)

finished3.gif
需求:上面的效果圖是在用戶從應(yīng)用程序的界面按下Home鍵退出,過一段時(shí)間再從后臺(tái)切換回來的時(shí)候,顯示一個(gè)密碼輸入的界面,只有當(dāng)用戶輸入了正確的密碼才能進(jìn)入退出前的界面.
需求分析:因?yàn)檫@個(gè)密碼輸入界面可能從任何應(yīng)用界面彈出,并且需要蓋在所有的界面上,所有它適合用一個(gè)UIWindow來實(shí)現(xiàn).代碼如下
1.創(chuàng)建一個(gè)PasswordInputWindow類繼承自UIWindow,在.h文件中實(shí)現(xiàn)兩個(gè)方法
@interface PasswordInputWindow : UIWindow
+(PasswordInputWindow *)sharedInstance;
- (void)show;
@end
2.在PasswordInputWindow類的.m文件中實(shí)現(xiàn)對應(yīng)的方法
+(PasswordInputWindow *)sharedInstance{
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc]initWithFrame:[UIScreen mainScreen].bounds];
});
return sharedInstance;
}
- (id)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 50, 200, 20)];
label.text = @"請輸入密碼";
[self addSubview:label];
UITextField * textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 80, 200, 20)];
textField.backgroundColor = [UIColor whiteColor];
textField.secureTextEntry = YES;
[self addSubview:textField];
UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(10, 110, 200, 44)];
[button setBackgroundColor:[UIColor blueColor]];
button.titleLabel.textColor = [UIColor blackColor];
[button setTitle:@"確定" forState:UIControlStateNormal];
[button addTarget:self action:@selector(compleBtnPressed) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
self.backgroundColor = [UIColor yellowColor];
self.textField = textField;
}
return self;
}
- (void)show{
[self makeKeyWindow];
self.hidden = NO;
}
- (void)compleBtnPressed{
if ([self.textField.text isEqualToString:@"abcd"]) {
[self.textField resignFirstResponder];
[self resignKeyWindow];
self.hidden = YES;
}else{
[self showErrorAlterView];
}
}
- (void)showErrorAlterView{
UIAlertView * view = [[UIAlertView alloc]initWithTitle:nil message:@"密碼錯(cuò)誤" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
[view show];
}
3.我們只需要在應(yīng)用進(jìn)入后臺(tái)的回調(diào)函數(shù)中,把自己的顯示出來即可.
//進(jìn)入后臺(tái)
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[PasswordInputWindow sharedInstance]show];
}
總結(jié):支付寶客戶端的手勢解鎖功能,應(yīng)用的啟動(dòng)介紹頁,應(yīng)用內(nèi)的彈窗廣告等都是利用的UIWindow一個(gè)很好的應(yīng)用.
參考資料:ios開發(fā)進(jìn)階(唐巧)