gpt4 book ai didi

iphone - 如何检测状态栏中的触摸

转载 作者:行者123 更新时间:2023-11-28 08:48:01 25 4
gpt4 key购买 nike

我的应用程序中有自定义 View ,用户可以滚动该 View 。然而,这个 View 并没有继承自 UIScrollView。现在我希望用户能够将此 View 滚动到顶部,就像任何其他可 ScrollView 所允许的那样。我认为没有直接的方法可以做到这一点。

Google 找到了一个解决方案:http://cocoawithlove.com/2009/05/intercepting-status-bar-touches-on.html这不再适用于 iOS 4.x。这是不行的。

我想创建一个 ScrollView 并将其保存在某个地方,只是为了捕捉它的通知,然后将它们转发到我的控件中。这不是解决我的问题的好方法,所以我正在寻找“更清洁”的解决方案。我喜欢上述链接到子类 UIApplication 的一般方法。但是什么 API 可以给我可靠的信息?

有什么想法,帮助等等...?

编辑: 我不喜欢当前解决方案的另一件事是,它仅在当前 View 没有任何 ScrollView 时才有效。滚动到顶部的手势只有在周围只有一个 ScrollView 时才有效。一旦将虚拟对象添加到另一个 ScrollView 的 View 中(有关详细信息,请参见下面的答案),该手势将被完全禁用。寻找更好解决方案的另一个原因......

最佳答案

最后,我根据此处的答案组装了可行的解决方案。感谢你们。

在某处声明通知名称(例如 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];
}

在所需 Controller 中观察通知(例如在 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")
}

关于iphone - 如何检测状态栏中的触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34777800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com