mercredi 9 août 2017

Swift If Statements

I have a registration view controller that 1) makes an empty textfield text red after the user has his the submit button and 2) shakes the empty textfield using a UIView.

 // if registered button is clicked and textfields are empty
        if usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty || emailTxt.text!.isEmpty || fullnameTxt.text!.isEmpty  {

        // display red placeholders for empty textfields
        usernameTxt.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.red])

        passwordTxt.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.red])

        emailTxt.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSForegroundColorAttributeName: UIColor.red])

        fullnameTxt.attributedPlaceholder = NSAttributedString(string: "Full Name", attributes:
            [NSForegroundColorAttributeName: UIColor.red])


    }

    // shake username textfield if it is empty
    if usernameTxt.text == "" {
        usernameTxt.shake()
    }

    // shake password textfield if it is empty
    if passwordTxt.text == "" {
        passwordTxt.shake()
    }

    // shake email textfield if it is empty
    if emailTxt.text == "" {
        emailTxt.shake()
    }

    // shake fullname textfield if it is empty
    if fullnameTxt.text == "" {
        fullnameTxt.shake()
    }


    } else {


        // remove keyboard
        self.view.endEditing(true)

However, if the textfield is empty, it still executes the red placeholder text as well as the textfield shake BUT it also executes code after the " } else { "

Does anyone have any suggestion on re writing this code so that the code after the else isn't executed? Thanks in advance

Aucun commentaire:

Enregistrer un commentaire