【问题标题】:iOS: How to detect keyboard change eventiOS:如何检测键盘更改事件
【发布时间】:2019-01-24 14:03:38
【问题描述】:

Xcode 9.2、iOS 10.0+、swift4。

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

那么,有什么功能或通知可以帮助我吗?

【问题讨论】:

    标签: ios swift uikeyboard


    【解决方案1】:

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

    【讨论】:

    • 我实现了相同但没有收到通知。我点击了地球图标,它显示了多个键盘,当我改变它时。它不会触发通知。 :(
    • 我得到了这个答案 stackoverflow.com/questions/46287136/… 。我使用 iOS10 模拟器进行了测试,是的,它会触发通知,但不会在 iOS 11 中触发。但是无论如何,谢谢。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      注册以接收以下通知:

      UITextInputCurrentInputModeDidChangeNotification

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

      【讨论】:

        【解决方案4】:

        随着 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
        
        }
        

        【讨论】:

          【解决方案5】:

          在 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)")
                  }
              }
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-06-16
            • 2014-11-24
            • 1970-01-01
            • 1970-01-01
            • 2014-06-22
            • 2014-03-31
            • 2017-09-07
            • 1970-01-01
            相关资源
            最近更新 更多