在不使用私有 API 的情况下获取当前的第一响应者 [英] Get the current first responder without using a private API
问题描述
我在一个多星期前提交了我的应用程序,今天收到了可怕的拒绝电子邮件.它告诉我我的应用程序无法被接受,因为我使用的是非公共 API;具体来说,它说,
I submitted my app a little over a week ago and got the dreaded rejection email today. It tells me that my app cannot be accepted because I'm using a non-public API; specifically, it says,
您的应用程序中包含的非公共 API 是 firstResponder.
The non-public API that is included in your application is firstResponder.
现在,有问题的 API 调用实际上是我在 SO 上找到的解决方案:
Now, the offending API call is actually a solution I found here on SO:
UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
如何在屏幕上显示当前的第一响应者?我正在寻找一种不会让我的应用被拒绝的方法.
How do I get the current first responder on the screen? I'm looking for a way that won't get my app rejected.
推荐答案
在我的一个应用程序中,我经常希望第一响应者在用户点击背景时辞职.为此,我在 UIView 上写了一个类别,在 UIWindow 上调用.
In one of my applications I often want the first responder to resign if the user taps on the background. For this purpose I wrote a category on UIView, which I call on the UIWindow.
以下内容基于此,应返回第一响应者.
The following is based on that and should return the first responder.
@implementation UIView (FindFirstResponder)
- (id)findFirstResponder
{
if (self.isFirstResponder) {
return self;
}
for (UIView *subView in self.subviews) {
id responder = [subView findFirstResponder];
if (responder) return responder;
}
return nil;
}
@end
iOS 7+
- (id)findFirstResponder
{
if (self.isFirstResponder) {
return self;
}
for (UIView *subView in self.view.subviews) {
if ([subView isFirstResponder]) {
return subView;
}
}
return nil;
}
斯威夫特:
extension UIView {
var firstResponder: UIView? {
guard !isFirstResponder else { return self }
for subview in subviews {
if let firstResponder = subview.firstResponder {
return firstResponder
}
}
return nil
}
}
Swift 中的使用示例:
if let firstResponder = view.window?.firstResponder {
// do something with `firstResponder`
}
这篇关于在不使用私有 API 的情况下获取当前的第一响应者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!