点击状态栏返回顶部

1、自定义window
2、转换坐标系
3、递归判断该控件是否在主窗口上显示
4、判断窗口的显示颜色

自定义window盖在状态栏上面, 之前遇到过报错,就是因为没有rootViewController, 后来写在dispatch_after就没事了
//
//  BSTopWindow.m
//  百思不得姐
//
//  Created by lxy on 16/6/6.
//  Copyright © 2016年 lxy. All rights reserved.
//

#import "BSTopWindow.h"

@implementation BSTopWindow

// 全局变量
static UIWindow *_window;

// 隐藏
+ (void)hide {
    _window.hidden = YES;
}

// 显示
+ (void)show {
    
    // 这样写就没事
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _window = [[UIWindow alloc] init];
        _window.windowLevel = UIWindowLevelAlert;
        _window.frame = [UIApplication sharedApplication].statusBarFrame;
        _window.backgroundColor = [UIColor clearColor];
        _window.hidden = NO;
        [_window addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(topWindowClick)]];
    });
    
}


/**
 * 这里一定是个类方法,监听窗口点击
 */
+ (void)topWindowClick {

    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [self searchScrollViewInView:window];
}

// 递归查找, 判断是否在主窗口上
+ (void)searchScrollViewInView:(UIView *)superView {
 
    for (UIScrollView *subview in superView.subviews) {
        
        // 得到subView在窗口中的frame, nil就是主窗口, 意思就是说,subview.frame从subview.superview坐标系转换为窗口坐标系
        CGRect newFrame = [subview.superview convertRect:subview.frame toView:[UIApplication sharedApplication].keyWindow];
        // 或者这样写
//        CGRect newFrame = [subview.superview convertRect:subview.frame toView:nil];
        
        BOOL isShowingOnWindow = subview.window == [UIApplication sharedApplication].keyWindow && !subview.isHidden && subview.alpha > 0.01 &&  CGRectIntersectsRect(newFrame, winBounds);
        
        // 如果是scrollView,滚动最顶部
        if ([subview isKindOfClass:[UIScrollView class]] && isShowingOnWindow) {
            CGPoint offset = subview.contentOffset;
            offset.y = -subview.contentInset.top;
            [subview setContentOffset:offset animated:YES];
        }
        
        // 继续查找子控件
        [self searchScrollViewInView:subview];
    }
    
}
@end

在其他控制器的viewDidAppear里面实现隐藏

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [BSTopWindow hide];
}

返回界面记得显示出来

- (IBAction)backLogin {
   
   [BSTopWindow show];
   
   [self dismissViewControllerAnimated:YES completion:nil];
   
}

你可能感兴趣的:(点击状态栏返回顶部)