我想根據密碼中的文本啟用和更改按鈕的顏色并確認密碼文本欄位。所以我在網上找到了這段代碼:
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文本欄位啟用或禁用繼續按鈕。但問題是,在填充password和confirmPassword文本password欄位后,如果我從欄位中洗掉文本,它仍會保持按鈕處于啟用狀態,并且只有在從文本欄位中洗掉文本時才會禁用它confirmPassword。如果我放在inpassword.delegate = self旁邊,當我在任何文本欄位中放入 1 個以上的字符時它會崩潰。confirmPassword.delgate = selfviewDidLoafd()
有沒有辦法通過始終檢查兩個文本欄位而不是一個文本欄位來啟用或禁用按鈕。確認密碼文本欄位?
uj5u.com熱心網友回復:
而不是使用 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
}
uj5u.com熱心網友回復:
我認為你錯過了一個測驗:而不是
if tfConfirmPasswordText.isEmpty
我會寫
if tfConfirmPasswordText.isEmpty || tfpasswordText.isEmpty
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366168.html
