手动创建UIWindow及UIWindowLevel的说明


关于UIWindowLevel
定义了UIWindow的层级,系统有3个取值

UIKIT_EXTERN const UIWindowLevel UIWindowLevelNormal;
UIKIT_EXTERN const UIWindowLevel UIWindowLevelAlert;
UIKIT_EXTERN const UIWindowLevel UIWindowLevelStatusBar;
NSLog(@"UIWindowLevelNormal:%f,UIWindowLevelAlert:%f,UIWindowLevelStatusBar:%f",UIWindowLevelNormal,UIWindowLevelAlert,UIWindowLevelStatusBar);

output:

UIWindowLevelNormal:0.000000,UIWindowLevelAlert:2000.000000,UIWindowLevelStatusBar:1000.000000;

系统默认层级是UIWindowLevelNormal,如果有UIAlertView,会创建层级为UIWindowLevelAlert的UIWindow,其UIWindowLevel值更高,覆盖在上面,实际应用中,UIWindowLevel值不止这3个

手动创建UIWindow,区别于UIView,UIWindow一旦被创建,将自动地添加到整个界面上~


手动创建UIWindow


#import "ViewController.h"

@interface ViewController ()
{
    UIWindow *_myWindow;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor redColor];

    //创建Button,点击创建UIWindow
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
    [button setTitle:@"创建window" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(_creatAction:) forControlEvents:UIControlEventTouchUpInside];
    button.center = self.view.center;
    [self.view addSubview:button];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)_creatAction:(UIButton *)btn {
    //创建一个UIWindow
    _myWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _myWindow.windowLevel = UIWindowLevelNormal;
    _myWindow.backgroundColor = [UIColor blackColor];
    _myWindow.alpha = 0.7;
    _myWindow.hidden = NO;

    //添加手势
    UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] init];
    [gesture addTarget:self action:@selector(hideWindow:)];
    [_myWindow addGestureRecognizer:gesture];

//    在window上添加一个UILabel
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 20)];
    label.text = @"LABEL";
    [label setTextColor:[UIColor whiteColor]];
    [_myWindow addSubview:label];
}

- (void)hideWindow:(UIGestureRecognizer *)gesture {
    _myWindow.hidden = YES;
    _myWindow = nil;
}

注意:
1、UIWindow不可滥用理应由ViewController实现的效果,就应该用ViewController addSubview来实现;
2、不可将需要弹出的界面都设置为单例,需要时调用显示,这会使得新创建的UIWindow一直得不到释放,出现多个UIWindow需要下过户有层级覆盖关系式,实现起来会比较复杂
(单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。)


以上为阅读《iOS开发进阶》第十二章摘记及练习


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值