一、UIWindow簡(jiǎn)介
UIWindow是最頂級(jí)的界面容器。
UIWindow繼承自UIView。
UIWindow的主要功能:
- 作為UIView的最頂級(jí)容器,包含應(yīng)用顯示所需要的所有的UIView。
- 傳遞觸摸消息和鍵盤事件給UIView。
UIWindow添加UIView有兩種方式:
- 通過(guò)調(diào)用addSubView方法。
- 通過(guò)設(shè)置其特有的rootViewController屬性。通過(guò)設(shè)置該屬性為要添加view對(duì)應(yīng)的UIViewController,UIWindow將自動(dòng)將其view添加到當(dāng)前window中,同時(shí)負(fù)責(zé)ViewController和view的生命周期。
二、UIWindow的使用
UIWindow通過(guò)UIWindowLevel設(shè)置window的層級(jí)。
例創(chuàng)建UIWindow的子類,實(shí)現(xiàn)調(diào)出輸入密碼界面。
#import <UIKit/UIKit.h>
@interface PasswordInputWindow : UIWindow
+ (PasswordInputWindow *)sharedInstance;
- (void)show;
@end
#import "PasswordInputWindow.h"
@implementation PasswordInputWindow{
UITextField *_textField;
}
+(PasswordInputWindow *)sharedInstance{
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc]initWithFrame:[UIScreen mainScreen].bounds];
});
return sharedInstance;
}
- (instancetype)initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if (self) {
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 50, 200, 20)];
label.text = @"請(qǐng)輸入密碼";
[self addSubview:label];
UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 80, 200, 20)];
textField.backgroundColor = [UIColor yellowColor];
textField.secureTextEntry = YES;
[self addSubview:textField];
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(10, 110, 200, 44)];
[button setBackgroundColor:[UIColor redColor]];
button.titleLabel.textColor = [UIColor whiteColor];
[button setTitle:@"登錄" forState:UIControlStateNormal];
[button addTarget:self action:@selector(completeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:button];
self.backgroundColor = [UIColor yellowColor];
_textField = textField;
}
return self;
}
- (void)show{
[self makeKeyWindow];
self.hidden = NO;
}
- (void)completeButtonPressed:(id)sender{
if ([_textField.text isEqualToString:@"1234"]) {
//正確
[_textField resignFirstResponder];
[self resignKeyWindow];
self.hidden = YES;
}else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"密碼輸入錯(cuò)誤" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
}
}
//后臺(tái)進(jìn)入時(shí)調(diào)用
[[PasswordInputWindow sharedInstance] show];
一般,手勢(shì)解鎖頁(yè)、啟動(dòng)介紹頁(yè)、應(yīng)用內(nèi)的通知提醒、彈窗廣告等適合用UIWindow來(lái)實(shí)現(xiàn)。