Statusbar 捕获状态栏的点击事件(ios 13及 ios 13 之前)

根据对应的系统版本,实现上会有差异。

iOS 13 之前

主要通过在 appdelegate 中 override touchbegan 事件来实现

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        
        // iOS 13 之后,点击状态栏的回调不会进入这里,而是在 UIStatusBarManager+CAPHandleTapAction 中处理
        if #available(iOS 13.0, *) {
            return
        }
        
        let statusBarRect = UIApplication.shared.statusBarFrame
        guard let touchPoint = event?.allTouches?.first?.location(in: self.window) else { return }
        
        if statusBarRect.contains(touchPoint) {
            NotificationCenter.default.post(name: StatusBarTappedNotification.name, object: nil)
        }
    }

还有一种是自己实现一个 UIWindow 覆盖在 状态栏的那一级 UIWindow 上。这里就不记录了


iOS 13 之后

iOS13: how to detect a status bar click event?

进入 iOS 13,touchBegan 的方法不会被调用到了。网上提供了一种思路来解决。

  • 简而言之,就是通过调用私有函数,来监听状态栏的点击事件。因此如果是上架的 App 不在本文的讨论范围内(因为你实现了也没用,上架会被拒)

实现思路

通过 objective-ccategory 去复写 UIStatusBarManager(iOS 13 之后才提供的 API) 中的私有方法 handleTapAction 实现监听。

注意,swift 的 extension 去实现复写私有函数的方法还没查到怎么做。如果有知道的欢迎补充。
如果工程采用了 swift,那么这里在添加 objective-c category 实现之后,要在 桥接的 bridge.h 中 import

UIStatusBarManager+CAPHandleTapAction.h

#import <UIKit/UIKit.h>

@interface UIStatusBarManager (CAPHandleTapAction)

/*
    使用 category 复写私有方法,捕获状态栏的点击事件
    仅当 iOS 13 以上系统,才去监听状态栏的点击事件,iOS 13 之前的,则在 appdelegate 中的 touchesBegan 捕获
 */

@end

UIStatusBarManager+CAPHandleTapAction.m

#import "UIStatusBarManager+CAPHandleTapAction.h"

@implementation UIStatusBarManager (CAPHandleTapAction)

- (void)handleTapAction:(id)callback {
    // 仅当 iOS 13 以上系统,才去监听状态栏的点击事件,iOS 13 之前的,则在 appdelegate 中的 touchesBegan 捕获
    if (@available(iOS 13.0, *)) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"StatusBarTappedNotification"
                                                            object:nil];
    }
}

@end
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 自从,搜狐博客各种毛病以后,不愿意写东西了,新出来的各种软件动不动就注册,麻烦的要死,我只是想随手写点碎碎念而已…...
    人生何处不矫情阅读 1,222评论 0 0
  • 以前有个男孩,他梦想有一天能迎娶邻居家青梅竹马的姑娘,因为父母是世交,所以他们理所当然的定了亲。男孩的梦想并不难...
    乔幽阅读 2,325评论 0 1
  • 人身体的一切疾病都可以从情绪中找到根源,严格来说,每一种情绪都需要找到一个突破口,如果不能得到合理的宣泄,...
    在路上_9baa阅读 3,142评论 0 0
  • 夏天最美的瞬间——遇见你 扎个小辫子,小钱如我 它是一株草,茂盛到把花盆抵满 垂下长枝条,乍一看是柳枝 为数不多几...
    HR_欣姐阅读 1,560评论 2 3
  • 儿子还不会说话,不过已经知道表达需求。 中午,他看到门口的树上挂了小灯笼想要,于是一直“啊啊啊”地给我指。后来。看...
    十月桃子阅读 4,075评论 0 0