iOS: How to detect keyboard change event

怎甘沉沦 提交于 2020-08-26 05:22:47

问题


Xcode 9.2, iOS 10.0+ , swift4.

I'm working on a project where user inputs english characters in UITextField and it converted to Japanese language characters. and it is working perfect. now, i want to allow user to input Japanese language characters direct from Japanese Keyboard.In this situation i want to know that the keyboard is changed from default to another type/language.

So, is there any function or Notification is available that can help me?


回答1:


You can use the UITextInputCurrentInputModeDidChange notification to detect when the current keyboard language changes.

NotificationCenter.default.addObserver(self, selector: #selector(inputModeDidChange), name: .UITextInputCurrentInputModeDidChange, object: nil)

@objc func inputModeDidChange(_ notification: Notification) {
    if let inputMode = notification.object as? UITextInputMode {
        if let lang = inputMode.primaryLanguage {
            // do something
        }
    }
}



回答2:


Register to receive the following notification:

UITextInputCurrentInputModeDidChangeNotification

And anytime the keyboard language changes, you'll receive a notification. You can get more info from UITextInputMode docs.




回答3:


With recent changes to iOS 12, swift 5.0 you can try:

func prepareForKeyboardChangeNotification() {
    NotificationCenter.default.addObserver(self, selector: #selector(changeInputMode), name: UITextInputMode.currentInputModeDidChangeNotification, object: nil)
}

@objc
func changeInputMode(notification: NSNotification) {
    let inputMethod = txtInput.textInputMode?.primaryLanguage
    //perform your logic here

}



回答4:


In newer Swift versions the notification has been renamed to UITextInputMode.currentInputModeDidChangeNotification



来源:https://stackoverflow.com/questions/51896904/ios-how-to-detect-keyboard-change-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!