Reputation: 2449
I created an UIAlertController
than created an UITextFields
in that controller. When I try to validate the entered texts to text fields, they return nil. Here is the code:
let loginWithMailAlert = UIAlertController(title: "Log In with Your Mail Address", message: "Please Enter Your E-Mail Address and Your Password", preferredStyle: UIAlertControllerStyle.Alert)
loginWithMailAlert.addTextFieldWithConfigurationHandler({[weak self](usernameField: UITextField!) in
usernameField.delegate = self
usernameField.placeholder = "E-Mail Address"
})
loginWithMailAlert.addTextFieldWithConfigurationHandler({[weak self](passwordField: UITextField!) in
passwordField.delegate = self
passwordField.placeholder = "Password"
passwordField.secureTextEntry = true
})
loginWithMailAlert.addAction(UIAlertAction(title: "Log In", style: UIAlertActionStyle.Default, handler:{
(loginWithMailAlert: UIAlertAction!) in
print("Pressed 'Log In'")
if self.usernameField.text == "faruk" && self.passwordField.text == "123" {
self.performSegueWithIdentifier("loginToMain", sender: nil)
}else{
print("Error")
print("Username::::\(self.usernameField.text as String!)")
}
}))
loginWithMailAlert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler:{
(loginWithMailAlert: UIAlertAction!) in
print("Pressed 'Cancel'")
}))
self.presentViewController(loginWithMailAlert, animated: true, completion: nil)
And here is the output :
Pressed 'Log In'
Error
Username::::
I added UITextFieldDelegate
to the class.
Can someone help?
Thanks.
Upvotes: 1
Views: 309
Reputation: 15512
Hmm for solving of you're issue just use my small code snipet. On ok button you could simply check value of the fields :
var loginTextField: UITextField?
var passwordTextField: UITextField?
let alertController = UIAlertController(title: "UIAlertController", message: "UIAlertController With TextField", preferredStyle: .Alert)
let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
//Check string hear !!
println(loginTextField?.text)
})
let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (action) -> Void in
println("Cancel Button Pressed")
}
alertController.addAction(ok)
alertController.addAction(cancel)
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
// Enter the textfiled customization code here.
loginTextField = textField
loginTextField?.placeholder = "User ID"
}
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
// Enter the textfiled customization code here.
passwordTextField = textField
passwordTextField?.placeholder = "Password"
passwordTextField?.secureTextEntry = true
}
presentViewController(alertController, animated: true, completion: nil)
Upvotes: 1