【问题标题】:check all textfields simultaneously & only enable button if they have text同时检查所有文本字段并仅在有文本时启用按钮
【发布时间】:2022-01-03 11:35:20
【问题描述】:

我想根据密码中的文本启用和更改按钮的颜色并确认密码文本字段。于是我在网上找到了这段代码:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let tfConfirmPasswordText = (tfConfirmPassword.text! as NSString).replacingCharacters(in: range, with: string)
    if tfConfirmPasswordText.isEmpty {
        btnContinue.backgroundColor = UIColor(named: "labelColor")
        btnContinue.isEnabled = false
    }
        else if tfPassword.text != "" && !tfConfirmPasswordText.isEmpty {
        btnContinue.backgroundColor = UIColor(named: "accentColor")
        btnContinue.isEnabled = true
    }
     return true
    }

此代码确实有效,并且使用这些条件,它将根据confirmPassword 文本字段启用或禁用继续按钮。 但问题是,在填充了passwordconfirmPassword 文本字段之后,如果我从password 字段中删除文本,它仍然保持启用按钮,并且只有在从confirmPassword 文本字段中删除文本时才会禁用它。 如果我在viewDidLoafd() 中将password.delegate = selfconfirmPassword.delgate = self 放在一起,当我在任何文本字段中输入超过1 个字符时,它就会崩溃。

有没有办法通过始终检查两个文本字段而不是一个文本字段来启用或禁用按钮..即。确认密码文本字段?

【问题讨论】:

    标签: ios swift xcode uikit uitextfield


    【解决方案1】:

    我没有使用 shouldChangeCharactersIn ,而是像下面这样使用它来使其工作

        override func viewDidLoad() {
                super.viewDidLoad()
              //initially at disabled 
                disabledButton()
                [tfPassword, tfConfirmPasswordText].forEach({ $0.addTarget(self, action: #selector(textFieldEditingDidChange), for: .editingChanged) })
            }
            
            @objc func textFieldEditingDidChange(sender: UITextField) {
                
                guard
                    let tfPasswordTxtValue = tfPassword.text, !tfPasswordTxtValue.isEmpty,
                    let tfConfirmPasswordTextValue = tfConfirmPasswordText.text, !tfConfirmPasswordTextValue.isEmpty
                        
                else {
                    disabledButton()
                    return
                }
                enableButton()
                
            }
    
         func disabledButton(){
          btnContinue.backgroundColor = UIColor(named: "labelColor")
          btnContinue.isEnabled = false
         }
    
        func enableButton(){
         btnContinue.isEnabled = true
       }
    

    【讨论】:

    • @Mel,检查并告诉我,它是否有效
    • 完美运行
    【解决方案2】:

    我认为您错过了一项测试: 而不是

    if tfConfirmPasswordText.isEmpty
    

    我会写

    if tfConfirmPasswordText.isEmpty || tfpasswordText.isEmpty
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 2017-10-25
      相关资源
      最近更新 更多