iOS:如何检测键盘更改事件

问题描述 投票:0回答:3

Xcode 9.2,iOS 10.0 +,swift4。

我正在开发一个项目,用户在UITextField中输入英文字符并将其转换为日语字符。它工作得很完美。现在,我想允许用户直接从日语键盘输入日语字符。在这种情况下,我想知道键盘从默认更改为另一种类型/语言。

那么,是否有任何功能或通知可以帮助我?

ios swift uikeyboard
3个回答
2
投票

您可以使用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
        }
    }
}

1
投票

注册以接收以下通知:

UITextInputCurrentInputModeDidChangeNotification

只要键盘语言发生变化,您就会收到通知。您可以从UITextInputMode docs获得更多信息。


0
投票

随着最近对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

}

0
投票

在较新的Swift版本中,通知已重命名为UITextInputMode.currentInputModeDidChangeNotification

© www.soinside.com 2019 - 2024. All rights reserved.