简体   繁体   English

如何以编程方式检查 iOS 应用程序中是否存在键盘?

[英]How can I programmatically check whether a keyboard is present in iOS app?

I need to check the condition of keyboard visibility in my iOS app.我需要在我的 iOS 应用程序中检查键盘可见性的条件。

Pseudocode:伪代码:

if(keyboardIsPresentOnWindow) {
    //Do action 1
}
else if (keyboardIsNotPresentOnWindow) {
    //Do action 2
}

How can I check this condition?我如何检查这种情况?

…or take the easy way: ...或采取简单的方法:

When you enter a textField, it becomes first responder and the keyboard appears.当您输入 textField 时,它将成为第一响应者并出现键盘。 You can check the status of the keyboard with [myTextField isFirstResponder] .您可以使用[myTextField isFirstResponder]检查键盘的状态。 If it returns YES , then the the keyboard is active.如果返回YES ,则键盘处于活动状态。

drawnonward's code is very close, but collides with UIKit's namespace and could be made easier to use. drawonward 的代码非常接近,但与 UIKit 的命名空间发生冲突,可以使其更易于使用。

@interface KeyboardStateListener : NSObject {
    BOOL _isVisible;
}
+ (KeyboardStateListener *)sharedInstance;
@property (nonatomic, readonly, getter=isVisible) BOOL visible;
@end

static KeyboardStateListener *sharedInstance;

@implementation KeyboardStateListener

+ (KeyboardStateListener *)sharedInstance
{
    return sharedInstance;
}

+ (void)load
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    sharedInstance = [[self alloc] init];
    [pool release];
}

- (BOOL)isVisible
{
    return _isVisible;
}

- (void)didShow
{
    _isVisible = YES;
}

- (void)didHide
{
    _isVisible = NO;
}

- (id)init
{
    if ((self = [super init])) {
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(didShow) name:UIKeyboardDidShowNotification object:nil];
        [center addObserver:self selector:@selector(didHide) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

@end

Create a UIKeyboardListener when you know the keyboard is not visible, for example by calling [UIKeyboardListener shared] from applicationDidFinishLaunching .当您知道键盘不可见时创建一个UIKeyboardListener ,例如通过从applicationDidFinishLaunching调用[UIKeyboardListener shared]

@implementation UIKeyboardListener

+ (UIKeyboardListener) shared {
    static UIKeyboardListener sListener;    
    if ( nil == sListener ) sListener = [[UIKeyboardListener alloc] init];

    return sListener;
}

-(id) init {
    self = [super init];

    if ( self ) {
        NSNotificationCenter        *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(noticeShowKeyboard:) name:UIKeyboardDidShowNotification object:nil];
        [center addObserver:self selector:@selector(noticeHideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    }

    return self;
}

-(void) noticeShowKeyboard:(NSNotification *)inNotification {
    _visible = true;
}

-(void) noticeHideKeyboard:(NSNotification *)inNotification {
    _visible = false;
}

-(BOOL) isVisible {
    return _visible;
}

@end

I think you need to use the notifications that are provided about the keyboard:我认为您需要使用提供的有关键盘的通知:

From: http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITextField_Class/Reference/UITextField.html来自: http : //developer.apple.com/iphone/library/documentation/UIKit/Reference/UITextField_Class/Reference/UITextField.html

Keyboard Notifications键盘通知

When the system shows or hides the keyboard, it posts several keyboard notifications.当系统显示或隐藏键盘时,它会发布多个键盘通知。 These notifications contain information about the keyboard, including its size, which you can use for calculations that involve moving views.这些通知包含有关键盘的信息,包括其大小,可用于涉及移动视图的计算。 Registering for these notifications is the only way to get some types of information about the keyboard.注册这些通知是获取有关键盘的某些类型信息的唯一方法。 The system delivers the following notifications for keyboard-related events:系统为键盘相关事件提供以下通知:

 * UIKeyboardWillShowNotification * UIKeyboardDidShowNotification * UIKeyboardWillHideNotification * UIKeyboardDidHideNotification

For more information about these notifications, see their descriptions in UIWindow Class Reference.有关这些通知的更多信息,请参阅 UIWindow 类参考中的说明。 For information about how to show and hide the keyboard, see Text and Web.有关如何显示和隐藏键盘的信息,请参阅文本和 Web。

Add an extension添加扩展

extension UIApplication {
    /// Checks if view hierarchy of application contains `UIRemoteKeyboardWindow` if it does, keyboard is presented
    var isKeyboardPresented: Bool {
        if let keyboardWindowClass = NSClassFromString("UIRemoteKeyboardWindow"),
            self.windows.contains(where: { $0.isKind(of: keyboardWindowClass) }) {
            return true
        } else {
            return false
        }
    }
}

Then check if keyboard is present,然后检查键盘是否存在,

if UIApplication.shared.isKeyboardPresented {
     print("Keyboard presented")
} else { 
     print("Keyboard is not presented")
}

Swift 3 Implementation Swift 3 实现

    import Foundation
class KeyboardStateListener: NSObject
{
    static let shared = KeyboardStateListener()
    var isVisible = false

    func start() {
        NotificationCenter.default.addObserver(self, selector: #selector(didShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(didHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func didShow()
    {
        isVisible = true
    }

    func didHide()
    {
        isVisible = false
    } 
}

Using the window subview hierarchy as indication for keyboard showing is a hack.使用窗口子视图层次结构作为键盘显示的指示是一种技巧。 If Apple changers their underlying implementation all these answers would break.如果 Apple 改变他们的底层实现,所有这些答案都会失效。

The correct way would be to monitor Keyboard show and hide notifications application wide such as inside your App Delegate:正确的方法是监视键盘显示和隐藏应用程序范围内的通知,例如在您的 App Delegate 内:

In AppDelegate.h:在 AppDelegate.h 中:

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (assign, nonatomic) BOOL keyboardIsShowing;

@end

In AppDelegate.m:在 AppDelegate.m 中:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // Monitor keyboard status application wide
    self.keyboardIsShowing = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
                                             name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:)
                                             name:UIKeyboardWillHideNotification object:nil];

    return YES;
}

- (void)keyboardWillShow:(NSNotification*)aNotification
{
    self.keyboardIsShowing = YES;
}

- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    self.keyboardIsShowing = NO;
}

Then you can check using:然后您可以使用以下方法进行检查:

BOOL keyboardIsShowing = ((AppDelegate*)[UIApplication sharedApplication].delegate).keyboardIsShowing;

It should be noted the keyboard show/hide notifications will not fire when user is using a bluetooth or external keyboard.应该注意的是,当用户使用蓝牙或外部键盘时,键盘显示/隐藏通知不会触发。

Now in iOS8 this solution of course doesn't work.现在在 iOS8 中,这个解决方案当然不起作用。 It was written initially for IOS4/5.它最初是为 IOS4/5 编写的。

Try this solution:试试这个解决方案:

- (BOOL) isKeyboardOnScreen 
{
    BOOL isKeyboardShown = NO;

    NSArray *windows = [UIApplication sharedApplication].windows;
    if (windows.count > 1) {
        NSArray *wSubviews =  [windows[1]  subviews];
        if (wSubviews.count) {
            CGRect keyboardFrame = [wSubviews[0] frame];
            CGRect screenFrame = [windows[1] frame];
            if (keyboardFrame.origin.y+keyboardFrame.size.height == screenFrame.size.height) {
                isKeyboardShown = YES;
            }
        }
    }

    return isKeyboardShown;
}

A few observations:一些观察:

The recommended pattern for a singleton object would be as follows.单例对象的推荐模式如下。 dispatch_once makes sure the class is initialised once in a thread-safe way, and the static variable isn't visible outside. dispatch_once 确保类以线程安全的方式初始化一次,并且静态变量在外部不可见。 And it's standard GCD, so no need to know about low level details of Objective-C.而且它是标准的 GCD,因此无需了解 Objective-C 的底层细节。

+ (KeyboardStateListener *)sharedInstance
{
    static KeyboardStateListener* shared;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[KeyboardStateListener alloc] init];
        // Other initialisations
    });

    return shared;
}

Usually you don't want to know just whether the keyboard is visible or not, but how big it is.通常你不想知道键盘是否可见,而是它有多大。 Keyboards don't all have the same size.并非所有键盘都具有相同的尺寸。 iPhone keyboards are smaller than iPad keyboards. iPhone 键盘比 iPad 键盘小。 So you'd want another property @property (readonly, nonatomic) CGRect keyboardRect;所以你需要另一个属性@property (readonly, nonatomic) CGRect keyboardRect; which is set in the noticeShowKeyboard: method like this:这是在 noticeShowKeyboard: 方法中设置的,如下所示:

NSValue* value = notification.userInfo [UIKeyboardFrameEndUserInfoKey];
_keyboardRect = value.CGRectValue;

Important to notice that the rectangle is in UIWindow coordinates and doesn't respect screen rotation.重要的是要注意矩形在 UIWindow 坐标中并且不考虑屏幕旋转。 So the caller would convert that rectangle by calling所以调用者会通过调用来转换那个矩形

KeyboardStateListener* listener = [KeyboardStateListener sharedInstance];
CGRect windowRect = listener.keyboardRect;
CGRect viewRect = [myView convertRect:windowRect fromView:self.window];

If the user rotates the screen while the keyboard is visible, the app will be told that the keyboard is hidden, then shown again.如果用户在键盘可见时旋转屏幕,应用程序将被告知键盘已隐藏,然后再次显示。 When it is shown, other views are most likely not rotated yet.显示时,其他视图很可能尚未旋转。 So if you observe keyboard hide/show events yourself, convert the coordinates when you actually need them, not in the notification.因此,如果您自己观察键盘隐藏/显示事件,请在实际需要时转换坐标,而不是在通知中。

If the user splits or undocks the keyboard, or uses a hardware keyboard, the notifications will always show the keyboard as hidden.如果用户拆分或取消键盘,或使用硬件键盘,通知将始终显示键盘为隐藏。 Undocking or merging the keyboard will send a "keyboard shown" notification.取消对接或合并键盘将发送“显示键盘”通知。

The listener must be initialised while the keyboard is hidden, otherwise the first notification will be missed, and it will be assumed that the keyboard is hidden when it's not.必须在键盘隐藏时初始化侦听器,否则将错过第一个通知,并假设键盘隐藏时隐藏。

So it is quite important to know what you actually want.因此,了解自己真正想要什么非常重要。 This code is useful to move things out of the way of the keyboard (with a split or undocked keyboard, that's the responsibility of the user).此代码对于将东西移出键盘很有用(对于拆分或未对接的键盘,这是用户的责任)。 It doesn't tell you whether the user can see a keyboard on the screen (in case of a split keyboard).它不会告诉您用户是否可以在屏幕上看到键盘(在拆分键盘的情况下)。 It doesn't tell you whether the user can type (for example when there is a hardware keyboard).它不会告诉您用户是否可以键入(例如,当有硬件键盘时)。 Looking at other windows doesn't work if the app creates other windows itself.如果应用程序本身创建了其他窗口,则查看其他窗口不起作用。

This is from the iOS Text Programming Guide published by Apple here: https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html这是来自 Apple 在此处发布的 iOS 文本编程指南: https : //developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html

Basically call "registerForKeyBoardNotifications" in your ViewDidLoad.基本上在您的 ViewDidLoad 中调用“registerForKeyBoardNotifications”。 Then every time the keyboard becomes active, "keyboardWasShown" is called.然后每次键盘激活时,都会调用“keyboardWasShown”。 And every time the keyboard disappears, "keyboardWillBeHidden" is called.每次键盘消失时,都会调用“keyboardWillBeHidden”。

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification {
    NSLog(@"Keyboard is active.");
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    // If active text field is hidden by keyboard, scroll it so it's visible
    // Your app might not need or want this behavior.
    CGRect aRect = self.view.frame;
    aRect.size.height -= kbSize.height;
    if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) {
        [self.scrollView scrollRectToVisible:activeField.frame animated:YES];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification {
    NSLog(@"Keyboard is hidden");
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

Swift implementation:斯威夫特实施:

class KeyboardStateListener: NSObject
{
  static var shared = KeyboardStateListener()
  var isVisible = false

  func start() {
    let nc = NSNotificationCenter.defaultCenter()
    nc.addObserver(self, selector: #selector(didShow), name: UIKeyboardDidShowNotification, object: nil)
    nc.addObserver(self, selector: #selector(didHide), name: UIKeyboardDidHideNotification, object: nil)
  }

  func didShow()
  {
    isVisible = true
  }

  func didHide()
  {
    isVisible = false
  } 
}

Because swift doesn't execute class load method on startup it is important to start this service on app launch:因为 swift 在启动时不执行类加载方法,所以在应用启动时启动这个服务很重要:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool
{
  ...    
  KeyboardStateListener.shared.start() 
}

This is my solution, it encapsulates everything into a single static method, and you can call it anywhere to check:这是我的解决方案,它将所有内容封装到一个静态方法中,您可以在任何地方调用它来检查:

+(BOOL)isKeyboardVisible{
    static id tokenKeyboardWillShow = nil;
    static id tokenKeyboardWillHide = nil;
    static BOOL isKbVisible = NO;
    @synchronized (self) {
        if (tokenKeyboardWillShow == nil){
            tokenKeyboardWillShow = [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
                @synchronized (self) {
                    isKbVisible = YES;
                }
            }];
        }

        if (tokenKeyboardWillHide == nil){
            tokenKeyboardWillHide = [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillHideNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
                @synchronized (self) {
                    isKbVisible = NO;
                }
            }];
        }
    }

    return isKbVisible;
}

And here's how to do it in Swift:下面是如何在 Swift 中做到这一点:

 func registerForKeyboardNotifications() {
    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "keyboardWasShown:",
        name: UIKeyboardDidShowNotification,
        object: nil)

    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "keyboardWillBeHidden:",
        name: UIKeyboardWillHideNotification,
        object: nil)
}

func keyboardWasShown(notification: NSNotification) {
    println("Keyboard was shown");
}

func keyboardWillBeHidden(notification: NSNotification) {
    println("Keyboard was dismissed");
}

Don't forget to unregister:不要忘记注销:

 override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self,
        name: UIKeyboardDidShowNotification,
        object: nil)

    NSNotificationCenter.defaultCenter().removeObserver(self,
        name: UIKeyboardWillHideNotification,
        object: nil)
}

And if you want to dismiss keyboard on pressing the "Return" button:如果您想在按下“返回”按钮时关闭键盘:

class ViewController: UIViewController, UITextFieldDelegate {

@IBOutlet weak var yourTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    registerForKeyboardNotifications()
    yourTextField.delegate = self
}

func textFieldShouldReturn(textField: UITextField!) -> Bool {
    self.view.endEditing(true);
    return false;
}

}

Try this function试试这个功能

BOOL UIKeyboardIsVisible(){

BOOL keyboardVisible=NO;
// Locate non-UIWindow.
UIWindow *keyboardWindow = nil;
for (UIWindow *testWindow in [[UIApplication sharedApplication] windows]) {
    if (![[testWindow class] isEqual:[UIWindow class]]) {
        keyboardWindow = testWindow;
        break;
    }
}
// Locate UIKeyboard.
for (UIView *possibleKeyboard in [keyboardWindow subviews]) {
    // iOS 4 sticks the UIKeyboard inside a UIPeripheralHostView.
    if ([[possibleKeyboard description] hasPrefix:@"<UIPeripheralHostView"]) {
        keyboardVisible=YES;
    }
    if ([[possibleKeyboard description] hasPrefix:@"<UIKeyboard"]) {
        keyboardVisible=YES;
        break;
    }
}
return keyboardVisible;

} }

from: iOS: How to access the `UIKeyboard`?来自: iOS:如何访问`UIKeyboard`?

BOOL isTxtOpen = [txtfieldObjct isFirstReponder]. BOOL isTxtOpen = [txtfieldObjct isFirstReponder]。 If it returns YES, then the the keyboard is active.如果返回 YES,则键盘处于活动状态。

To check weather keyboard is appeared, we can use the Keyboard predefined notifications.要检查天气键盘是否出现,我们可以使用键盘预定义通知。

UIKeyboardDidShowNotification ,UIKeyboardDidHideNotification UIKeyboardDidShowNotification ,UIKeyboardDidHideNotification

For example I can use the following code to listen the keyboard notification例如我可以使用下面的代码来监听键盘通知

// Listen for keyboard appearances and disappearances // 监听键盘出现和消失

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardDidShow:)
                                             name:UIKeyboardDidShowNotification
                                           object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardDidHide:)
                                             name:UIKeyboardDidHideNotification
                                           object:nil];

in the methods I can get notifications在我可以收到通知的方法中

- (void)keyboardDidShow: (NSNotification *) notifyKeyBoardShow{
    // key board is closed
}

- (void)keyboardDidHide: (NSNotification *) notifyKeyBoardHide{
    // key board is opened
}

Swift 4斯威夫特 4

extension UIViewController {
    func registerKeyboardNotifications() {
        let center = NotificationCenter.default
        center.addObserver(self, selector: #selector(keyboardWillBeShown(note:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
        center.addObserver(self, selector: #selector(keyboardWillBeHidden(note:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
    }

    func removeKeyboardNotifications() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)

    }

    @objc
    func keyboardWillBeShown(note: Notification) {}

    @objc
    func keyboardWillBeHidden(note: Notification) {}

}

final class MyViewController: UIViewController {

    // MARK: - Properties
    var isKeyboardVisible = false

    // MARK: - Life Cycle
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        registerKeyboardNotifications()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        removeKeyboardNotifications()
    }

    // MARK: - Keyboard Handling
    override func keyboardWillBeShown(note: Notification) {
        isKeyboardVisible = true
        let userInfo = note.userInfo
        let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect
        let contentInset = UIEdgeInsetsMake(0.0, 0.0, keyboardFrame.height, 0.0)
        tableView.contentInset = contentInset
    }

   override func keyboardWillBeHidden(note: Notification) {
        tableView.contentInset = .zero
        isKeyboardVisible = false
   }

   // MARK: - Test
   fileprivate func test() {
        if isKeyboardVisible { // do something
        }
   }
}

SwiftUI - Full Example SwiftUI - 完整示例

import SwiftUI

struct ContentView: View {
    
    @State private var text = defaultText
    
    @State private var isKeyboardShowing = false
    
    private static let defaultText = "write something..."
    
    private var gesture = TapGesture().onEnded({_ in
        UIApplication.shared.endEditing(true)
    })
    
    var body: some View {
        
        ZStack {
            Color.black
            
            VStack(alignment: .leading) {
                TextField("placeholder", text: $text)
                    .foregroundColor(.white)
                    .padding()
                    .background(Color.green)
            }
            
            .padding()
        }
        .edgesIgnoringSafeArea(.all)
        .onChange(of: isKeyboardShowing, perform: { (isShowing) in
            if isShowing {
                if text == Self.defaultText { text = "" }
            } else {
                if text == "" { text = Self.defaultText }
            }
        })
        .simultaneousGesture(gesture)
        .onReceive(NotificationCenter.default
                    .publisher(for: UIResponder.keyboardWillShowNotification), perform: { (value) in
                        isKeyboardShowing = true
                    })
        .onReceive(NotificationCenter.default
                    .publisher(for: UIResponder.keyboardWillHideNotification), perform: { (value) in
                        isKeyboardShowing = false
                    })
    }
}

extension UIApplication {
    func endEditing(_ force: Bool) {
        self.windows
            .filter{$0.isKeyWindow}
            .first?
            .endEditing(force)
    }
}

You can iteratively check all textviews, textfields, and labels in the subviews of a parent view to see if any are the first responder with something like this:您可以迭代地检查父视图子视图中的所有文本视图、文本字段和标签,以查看是否有类似以下内容的第一响应者:

-(BOOL)isKeyboardActiveInView:(UIView *)view {
    for (UIView *anyView in [view subviews]) {
        if ([anyView isKindOfClass:[UITextField class]]) {
            if (((UITextField *)anyView).isFirstResponder) {
                return YES;
            }
        } else if ([anyView isKindOfClass:[UILabel class]]) {
            if (((UILabel *)anyView).isFirstResponder) {
                return YES;
            }
        } else if ([anyView isKindOfClass:[UITextView class]]) {
            if (((UITextView *)anyView).isFirstResponder) {
                return YES;
            }
        } else {
            if ([self isKeyboardActiveInView:anyView]) {
                return YES;
            }
        }
    }
    return NO;
}

SWIFT 4.2 / SWIFT 5 SWIFT 4.2 / SWIFT 5

class Listener {
   public static let shared = Listener()
   var isVisible = false

   // Start this listener if you want to present the toast above the keyboard.
   public func startKeyboardListener() {
      NotificationCenter.default.addObserver(self, selector: #selector(didShow), name: UIResponder.keyboardWillShowNotification, object: nil)
      NotificationCenter.default.addObserver(self, selector: #selector(didHide), name: UIResponder.keyboardWillHideNotification, object: nil)
   }

   @objc func didShow() {
     isVisible = true
   }

    @objc func didHide(){
       isVisible = false
    }
}

I think this may help u,我想这可能会帮助你,

+(BOOL)isKeyBoardInDisplay  {

    BOOL isExists = NO;
    for (UIWindow *keyboardWindow in [[UIApplication sharedApplication] windows])   {
        if ([[keyboardWindow description] hasPrefix:@"<UITextEffectsWindow"] == YES) {
            isExists = YES;
        }  
    }

    return isExists;
}

thanks,谢谢,

Naveen Shan纳文山

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在我的iOS应用程序中以编程方式引发键盘事件 - How can I raise Keyboard events programmatically in my iOS application 如何在IOS中以编程方式表示键盘触摸事件? - How can I represent a keyboard touch event programmatically in IOS? 如何以编程方式检查用户是否为 iOS 应用程序启用了计划摘要通知? - How to check programmatically whether the Scheduled Summary notifications is enabled by a user for an iOS app? 如何检查 iOS/iPadOS 中是否启用了暗模式? - How can I check whether dark mode is enabled in iOS/iPadOS? 如何检查 iOS 设备上是否启用了 Motion &amp; Fitness? - How can I check whether or not Motion & Fitness is enabled on an iOS device? 如何检查iOS键盘中是否启用了听写功能? - How to check whether Dictation is enabled in iOS Keyboard.? 如何验证我的应用程序是否支持iOS 4.3 - How can I verify whether my app supports iOS 4.3 or not 如何以编程方式检查 ios 设备的当前 userInterfaceStyle? - How can I check ios device's current userInterfaceStyle programmatically? iOS如何检查i是否完成循环? - IOS how to check whether the i finish looping? 如何以编程方式检查用户是否已登录到应用商店 - How to check programmatically whether a user is logged in to the app store
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM