iOS 状态栏添加点击事件

第一步:在AppDelegate.m 中添加以下代码

#pragma mark - Status Bar Touch Event

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];

    CGPoint touchLocation = [[[event allTouches] anyObject] locationInView:self.window];
    CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;

    if (CGRectContainsPoint(statusBarFrame, touchLocation))
    {
        [self statusBarTouchedAction];
    }
}

- (void)statusBarTouchedAction {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"statusBarTappedNotification" object:nil];
}

第二步:在要触发点击事件的控制器中添加以下代码

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
        
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarAction:) name:@"statusBarTappedNotification" object:nil];
    
}

- (void)statusBarAction:(NSNotification *)noti{
   //your code

}


注意:旧方法在iOS 13中已经废弃,因为iOS 13中采用多window模式,状态栏touch事件无法被捕捉。因此在iOS 13上获取statusBar点击事件只能使用另一种方法。通过hook私有方法来获取点击事件

第一步:新建分类文件
UIStatusBarManager+TapAction.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIStatusBarManager (TapAction)

@end

NS_ASSUME_NONNULL_END

UIStatusBarManager+TapAction.m

#import "UIStatusBarManager+TapAction.h"

#if TARGET_OS_IPHONE
#import <objc/runtime.h>
#import <objc/message.h>
#else
#import <objc/objc-class.h>
#endif

@implementation UIStatusBarManager (TapAction)
+ (void)load
{
    Method orignalMethod = class_getInstanceMethod(self, @selector(handleTapAction:));
    Method swizzledMethod = class_getInstanceMethod(self, @selector(statusBarTouchedAction:));
    method_exchangeImplementations(orignalMethod, swizzledMethod);
}

- (void)statusBarTouchedAction:(id)sender{
    [self statusBarTouchedAction:sender];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"statusBarTappedNotification" object:nil];
}

@end

第二步:在要触发点击事件的控制器中添加以下代码

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
        
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarAction:) name:@"statusBarTappedNotification" object:nil];
    
}

- (void)statusBarAction:(NSNotification *)noti{
   //your code

}


参考:# iOS13: how to detect a status bar click event?

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

推荐阅读更多精彩内容