iOS: 为statusbar状态栏添加点击事件

iOS App在点击状态栏时可以自动滚动到顶部。这个属性可以通过scrollsToTop来控制,当存在多个scrollview时,可以关闭其他的scrollview的scrollsToTop,只开启某一个scrollview的scrollsToTop属性,来响应回到顶部的事件。

但当多个scrollview嵌套时,可能存在上述做法都做了,但还是不响应回到顶部的事件,这个时候我们可以给statusbar上覆盖上一个window,用这个window来接收响应事件。

@property (nonatomic,strong) UIWindow *coverWindow;

 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 *  NSEC_PER_SEC)), 
    dispatch_get_main_queue(), ^{  
    _coverWindow =[[UIWindow alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 20)];
    _coverWindow.hidden = NO;
    _coverWindow.backgroundColor = [UIColor clearColor];
    _coverWindow.windowLevel = UIWindowLevelStatusBar + 1;//优先级比statusbar高一点,盖住statusbar
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapWindowScrollsToTop)];
    [_coverWindow addGestureRecognizer:tap];
    [_coverWindow makeKeyAndVisible];//让window变成主window,并显示出来
});

Tips:延时创建是为了等控制器先创建好后再添加window。

当不想要这个新添加的window时,只需要将其置为nil,就被移除释放掉了。

要注意,如果你需要在window上添加类似UIAlertView等控件,而此时新加的window由于被注册成了keywindow,所以加的UIAlertView都被添加到新自定义的window上,所以我想到了下边的办法。
_coverWindow变成keywindow之前,先获取原来的keywindow。

UIWindow * window = [UIApplication sharedApplication].keyWindow;

你应该猜到了,我要干嘛。

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    _coverWindow =[[UIWindow alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 20)];
    _coverWindow.hidden = NO;
    _coverWindow.backgroundColor = [UIColor clearColor];
    _coverWindow.windowLevel = UIWindowLevelStatusBar + 1;//优先级比statusbar高一点,盖住statusbar
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapWindowScrollsToTop)];
    [_coverWindow addGestureRecognizer:tap];
    [_coverWindow makeKeyAndVisible];//让window变成主window,并显示出来
    [window makeKeyWindow];//把原来的window在变成主window
});

在原来代码基础上,最后再加一句,这样,在新加的window变成主window后,把原来获取的window 接着变成主window。这样就不影响之后的往keywindow上添加的控件的显示了。

当然这只是我暂时想到的办法,有什么更好的方法,欢迎留言给我。

你可能感兴趣的:(iOS: 为statusbar状态栏添加点击事件)