【问题标题】:Hiding keyboard in view with multiple text fields in Swift在 Swift 中使用多个文本字段隐藏键盘
【发布时间】:2017-12-15 06:16:26
【问题描述】:

我有 3 个文本字段和一个 pickerView,当其中一个字段 (m_unit) 处于活动状态时,它会取消隐藏,所以我试图为这个隐藏键盘:

func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.returnKeyType = UIReturnKeyType.done
        save_button.isEnabled = false
        if textField == self.m_unit {
            self.drop_down.isHidden = false
            textField.endEditing(true)
        }

如果在点击m_unit 时没有其他编辑文本字段,则可以正常工作。在这种情况下,键盘不会消失。换句话说,当我点击某个文本字段时,它会显示键盘,然后我点击 m_unit 字段,但键盘仍然存在。我该如何解决这个问题?

【问题讨论】:

    标签: ios swift view keyboard textfield


    【解决方案1】:

    textField.resignFirstResponder()

    【讨论】:

      【解决方案2】:

      试试这个代码:

      func textFieldDidBeginEditing(_ textField: UITextField) {
              textField.returnKeyType = UIReturnKeyType.done
              save_button.isEnabled = false
              if textField == self.m_unit {
                  textField.resignFirstResponder() 
                  self.drop_down.isHidden = false
              }
      

      【讨论】:

        【解决方案3】:

        您似乎想为给定的文本字段显示UIPickerView 而不是键盘 (m_unit) 我会使用不同的方法:)

        您可以将 UIPickerView 设置为 UITextField 的 inputView(在 viewDidLoadloadView 中)

        self.m_unit.inputView = yourPickerView
        

        你也可以检查这个问题: UIPickerView as inputView of UITextField 这可能与您的重复;)

        【讨论】:

        • 我将此行添加到viewDidLoad,但在点击 m_unit 文本字段时出现错误。控制台:由于未捕获的异常“UIViewControllerHierarchyInconsistency”而终止应用程序,原因:“子视图控制器:<0x7f9bc7d27b10><0x7f9bc7c04700><0x7f9bc88ae400>
        【解决方案4】:
        1. 选择器视图文本字段 false

            func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
          //print("While entering the characters this method gets called")
          
          if(textField == pickerViewTextField){
              return false;
             }
          
            return true;
           }
          
        2. 用户文本字段委托波纹管代码在按下返回时隐藏键盘

            func textFieldShouldReturn(_ textField: UITextField) -> Bool {
          
             textField.resignFirstResponder()
             return true
           }
          
        3. 别忘了使用 UITextFieldDelegate

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-12-22
          • 2014-03-18
          • 2011-01-19
          • 1970-01-01
          • 1970-01-01
          • 2019-10-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多