问题
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