最后,我从这里的答案中收集了可行的解决方案。谢谢你们。
在某处声明通知名称(例如 AppDelegate.h):
static NSString * const kStatusBarTappedNotification = @"statusBarTappedNotification";
在您的 AppDelegate.m 中添加以下行:
#pragma mark - Status bar touch tracking
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
CGPoint location = [[[event allTouches] anyObject] locationInView:[self window]];
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
if (CGRectContainsPoint(statusBarFrame, location)) {
[self statusBarTouchedAction];
}
}
- (void)statusBarTouchedAction {
[[NSNotificationCenter defaultCenter] postNotificationName:kStatusBarTappedNotification
object:nil];
}
在所需的控制器中观察通知(例如在 viewWillAppear 中):
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(statusBarTappedAction:)
name:kStatusBarTappedNotification
object:nil];
正确移除观察者(例如在 viewDidDisappear 中):
[[NSNotificationCenter defaultCenter] removeObserver:self name:kStatusBarTappedNotification object:nil];
实现通知处理回调:
- (void)statusBarTappedAction:(NSNotification*)notification {
NSLog(@"StatusBar tapped");
//handle StatusBar tap here.
}
希望它会有所帮助。
Swift 3 更新
在 iOS 9+ 上测试并运行。
在某处声明通知名称:
let statusBarTappedNotification = Notification(name: Notification.Name(rawValue: "statusBarTappedNotification"))
跟踪状态栏的触摸和发布通知。将以下行添加到您的 AppDelegate.swift:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
let statusBarRect = UIApplication.shared.statusBarFrame
guard let touchPoint = event?.allTouches?.first?.location(in: self.window) else { return }
if statusBarRect.contains(touchPoint) {
NotificationCenter.default.post(statusBarTappedNotification)
}
}
必要时注意通知:
NotificationCenter.default.addObserver(forName: statusBarTappedNotification.name, object: .none, queue: .none) { _ in
print("status bar tapped")
}