kings09045 kings09045 - 3 months ago 23
Swift Question

swift get nil value in alertview textfield

I use SCLAlertView Framework as my Alert View.
https://github.com/vikmeup/SCLAlertView-Swift

I create an alertview with textfield. Here is the code.

let emailSubmit: UITextField = UITextField()
let passwordSubmit: UITextField = UITextField()
var email: String?
var password: String?

//This function call when loginbutton tapped
func showLogin(){

let alertView = SCLAlertView()

let emailSubmit = alertView.addTextField("Enter your Email")
let passwordSubmit = alertView.addTextField("Password")

email = emailSubmit.text
password = passwordSubmit.text
passwordSubmit.secureTextEntry = true

alertView.addButton("Confirm", target:self, selector:#selector(ViewController.submitLogin))

alertView.showTitle(
"Login",
subTitle: "",
duration: nil,
completeText: "Cancel",
style: .Info)
}


It required me to add a function for the button. The function name is submitLogin. It use to send the login detail(
textfield.text
) to the back-end server. However, it only return nil value after i click the submit button
It is the submit login button function

func submitLogin(){
let email = emailSubmit.text!
let password = passwordSubmit.text!

print("\(email),\(password)")
}


However, It display nil when I click the submit button Can anyone point out what's wrong with the code?

Answer

The Code should be like this:

var email: String?
var password: String?

//This function call when loginbutton tapped
@IBAction func showLogin(){

    let alertView = SCLAlertView()

    let emailSubmit = alertView.addTextField("Enter your Email")
    let passwordSubmit = alertView.addTextField("Password")

    passwordSubmit.secureTextEntry = true

    alertView.addButton("Confirm") {
        self.email = emailSubmit.text
        self.password = passwordSubmit.text

        self.submitLogin()
    }

    alertView.showTitle(
        "Login",
        subTitle: "",
        duration: nil,
        completeText: "Cancel",
        style: .Info)
}

func submitLogin(){
    print("\(email),\(password)")
}

Explanation:

In your code the line password = passwordSubmit.text is setting value of var password to nil before user presses the confirm button, same with var email.

And there is not need to Define email and password textfields, since alertview will create textfields within itself.

Comments