Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

validation - Swift - validating UITextField

I have these outlets in my app:

@IBOutlet var name1: UITextField!

@IBOutlet var name2: UITextField!

@IBOutlet var name3: UITextField!

@IBOutlet var name4: UITextField!

@IBOutlet var newButton: UIButton!

What I tried to do is the following:

Every time the user types something in one of these four UITextFields or deletes something, I want to check if any UITextField is empty

If any UITextField is empty, the button should be disabled.

If all UITextFields are set (not empty), the button should be enabled.

My code:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    setButton()

    return true
}

func setButton() {

    let inputValid = checkInput()

    if inputValid {

        newButton.enabled = true

    } else {

        newButton.enabled = false

    }

}

func checkInput() -> Bool {

    let name1Value = name1.text
    let name2Value = name2.text
    let name3Value = name3.text
    let name4Value = name4.text

    if !name1Value.isEmpty && !name2Value.isEmpty && !name3Value.isEmpty && !name4Value.isEmpty {

        return true

    }

    return false

}

Ok, it works 50% for now.

When I type one character in each UITextField, the button is still disabled.

When I add a second one to any UITextField, the button gets enabled etc...

Can anyone help me with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Alternatively, you can use this, which is called every time a key is pressed:

name1.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
name2.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
name3.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
name4.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)


func textFieldDidChange(textField: UITextField) {
    if name1.text?.isEmpty || name2.text?.isEmpty || name3.text?.isEmpty || name4.text?.isEmpty {
        //Disable button
    } else {
        //Enable button
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...