代码之家  ›  专栏  ›  技术社区  ›  Vatsal Shukla

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

  •  0
  • Vatsal Shukla  · 技术社区  · 7 年前

    Xcode 9.2、iOS 10.0+、swift4。

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

    3 回复  |  直到 7 年前
        1
  •  3
  •   rmaddy    7 年前

    你可以使用 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
            }
        }
    }
    
        2
  •  1
  •   Sylvan D Ash    7 年前

    注册以接收以下通知:

    UITextInputCurrentInputModeDidChangeNotification

    只要键盘语言改变,你就会收到通知。你可以从 UITextInputMode 文件。

        3
  •  1
  •   Amir.n3t    7 年前

    通过最近对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
    
    }
    
        4
  •  1
  •   ph1lb4    6 年前

    UITextInputMode.currentInputModeDidChangeNotification