【发布时间】:2019-01-24 14:03:38
【问题描述】:
Xcode 9.2、iOS 10.0+、swift4。
我正在开发一个项目,用户在UITextField 中输入英文字符并将其转换为日文字符。它工作完美。现在,我想允许用户直接从日文键盘输入日文字符。在这种情况下,我想知道键盘已从默认更改为另一种类型/语言。
那么,有什么功能或通知可以帮助我吗?
【问题讨论】:
标签: ios swift uikeyboard
Xcode 9.2、iOS 10.0+、swift4。
我正在开发一个项目,用户在UITextField 中输入英文字符并将其转换为日文字符。它工作完美。现在,我想允许用户直接从日文键盘输入日文字符。在这种情况下,我想知道键盘已从默认更改为另一种类型/语言。
那么,有什么功能或通知可以帮助我吗?
【问题讨论】:
标签: ios swift uikeyboard
您可以使用UITextInputCurrentInputModeDidChange 通知来检测当前键盘语言何时发生变化。
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
}
}
}
【讨论】:
在较新的 Swift 版本中,通知已重命名为 UITextInputMode.currentInputModeDidChangeNotification
【讨论】:
注册以接收以下通知:
UITextInputCurrentInputModeDidChangeNotification
只要键盘语言发生变化,您就会收到通知。您可以从UITextInputMode docs 获取更多信息。
【讨论】:
随着 iOS 12 最近的变化,你可以试试 swift 5.0:
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
}
【讨论】:
在 Swift 4.2 中
//keyboard type change
NotificationCenter.default.addObserver(self, selector: #selector(inputModeDidChange), name: UITextInputMode.currentInputModeDidChangeNotification, object: nil)
@objc func inputModeDidChange(_ notification: Notification) {
if let inputMode = notification.object as? UITextInputMode {
if let lang = inputMode.primaryLanguage {
print("langueage:: \(lang)")
}
}
}
【讨论】: