文本字段为空时如何启用按钮

时间:2017-11-15 08:25:00

标签: ios swift button input uitextfield

first second theard这是我的代码,但问题是用户开始输入后按钮启动启用 第二个问题是我想改变他的颜色

     override func viewDidLoad() {
             handleTextField()
        fullname.delegate = self
        username.delegate = self
        email.delegate = self
        password.delegate = self
    }


        func handleTextField(){
                fullname.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
                username.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
                email.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
                password.addTarget(self, action: #selector(SignupVC.textFieldDidChange), for: UIControlEvents.editingChanged)
            }
            @objc func textFieldDidChange(){
                guard let username = username.text, !username.isEmpty, let email = email.text, !email.isEmpty, let fullname = fullname.text, !fullname.isEmpty, let password = password.text, !password.isEmpty else {
                    signupBtn.setTitleColor(UIColor.lightText, for: UIControlState.normal)
                    signupBtn.isEnabled = false
                    return 
                }
                signupBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
                signupBtn.isEnabled = true
            }

1 个答案:

答案 0 :(得分:0)

您应该实现UITextFieldDelegate,如下所示:

override func viewDidLoad() {
        super.viewDidLoad()
        fullname.delegate = self
        username.delegate = self
        email.delegate = self
        password.delegate = self

        signupBtn.isEnabled = false
    }

    func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) {
        if reason == .committed {
            //textFieldDidChange()
        }
    }

   func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == username, let text = textField.text, !text.isEmpty { // your are typing the 2nd textfield
        if let text = fullname.text, !text.isEmpty { // and the 1st textfield filled
            signupBtn.isEnabled = true
            signupBtn.setTitleColor(.green, for: .normal)
        }
    }
    return true
}

    func textFieldDidChange() {
        guard let username = username.text, !username.isEmpty, let email = email.text, !email.isEmpty, let fullname = fullname.text, !fullname.isEmpty, let password = password.text, !password.isEmpty else {
            signupBtn.setTitleColor(UIColor.lightText, for: UIControlState.normal)
            signupBtn.isEnabled = false
            return
        }
        signupBtn.setTitleColor(UIColor.white, for: UIControlState.normal)
        signupBtn.isEnabled = true
    }