iOS开发之UIWindow的使用

一、UIWindow简介

UIWindow是最顶级的界面容器。
UIWindow继承自UIView。

UIWindow的主要功能:

  1. 作为UIView的最顶级容器,包含应用显示所需要的所有的UIView。
  2. 传递触摸消息和键盘事件给UIView。

UIWindow添加UIView有两种方式:

  1. 通过调用addSubView方法。
  2. 通过设置其特有的rootViewController属性。通过设置该属性为要添加view对应的UIViewController,UIWindow将自动将其view添加到当前window中,同时负责ViewController和view的生命周期。

二、UIWindow的使用

UIWindow通过UIWindowLevel设置window的层级。
例创建UIWindow的子类,实现调出输入密码界面。

#import 

@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 = @"请输入密码";
        [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:@"密码输入错误" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    

    }
}

//后台进入时调用

    [[PasswordInputWindow sharedInstance] show];

一般,手势解锁页、启动介绍页、应用内的通知提醒、弹窗广告等适合用UIWindow来实现。

你可能感兴趣的:(iOS开发之UIWindow的使用)