思路
- 找到keyWindow
- 通过keyWindow找到firstResponder
- 使用firstResponder调用resignFirstResponder隐藏键盘
代码
/// 隐藏键盘
- (void)_hiddenKeyBoard {
UIWindow *keyWindow = [self getKeyWindow];
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
if ([keyWindow respondsToSelector:@selector(firstResponder)]) {
UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
[firstResponder resignFirstResponder];
}
#pragma clang diagnostic pop
}
//获取KeyWindow
- (UIWindow *)getKeyWindow {
if (@available(iOS 13.0, *)) {
for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
if (windowScene.activationState == UISceneActivationStateForegroundActive) {
for (UIWindow *window in windowScene.windows) {
if (window.isKeyWindow) {
return window;
break;
}
}
}
}
}
else {
return [UIApplication sharedApplication].keyWindow;
}
return nil;
}