JJHA
JJHA

Reputation: 76

how to check textfield is not empty and button enable

I want to check textfield is empty

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if !text.isEmpty {
            self.completeRegisterBtn.isEnabled = true
        } else {
            self.completeRegisterBtn.isEnabled = false
        }
        
        return true
    }

This is my code but it is only check input new text. I have already input textfields by data. How can i check?

Furthermore not only want to check textfield but also a button(from 2 button) is selected check

Please help me. Thank you

Upvotes: 0

Views: 1556

Answers (4)

Solayman Rana
Solayman Rana

Reputation: 331

Try this

if let text = textfield.text, !text.isEmpty {
    completeRegisterBtn.isEnabled = true
} else {
    completeRegisterBtn.isEnabled = false
}

Upvotes: 0

Vishal Zaveri
Vishal Zaveri

Reputation: 1557

Just make function like this and call where you want to use this

func dataValidation(text: String) {

  btn.isEnable = (text.isEmpty ?? false) ? false : true 

}

how to use:

dataValidation(text: "test") 

Upvotes: 0

Arun sharma
Arun sharma

Reputation: 652

Answer as per your comment:

if textField.text != "" && btn.isSelected {
            
 }

Upvotes: 0

sid_patel_1211
sid_patel_1211

Reputation: 153

I have attached the code how to check that textFiled is empty or not

let txtField = UITextField()
txtField.text = "testing"
if txtField.text != "" {
    btn_Pause.isEnabled = true
} else {
    btn_Pause.isEnabled = false
}

-> Using isEmpty function

if txtField.text?.isEmpty == true {
    btn_Pause.isEnabled = false
} else {
    btn_Pause.isEnabled = true
}

-> Using character count

if txtField.text?.count ?? 0 > 0 {
    btn_Pause.isEnabled = true
} else {
    btn_Pause.isEnabled = false
}

Upvotes: 1

Related Questions