[英]Swift Error Alert Action Performs Segue, But Successful Action Does Not
我遇到了我的注冊控制器的問題,當用戶將任何文本字段留空時,我的錯誤處理程序都會發出警報,提示單擊“確定”后,會將用戶發送到僅在注冊成功后才出現的下一個視圖控制器。 當用戶成功注冊時,情況正好相反。 我的信息已記錄,但下一個視圖控制器未發生中斷。 我應該如何防止這種情況發生?
import UIKit
class UserRegistrationViewController: UIViewController {
@IBOutlet var usernameTextField: UITextField!
@IBOutlet var emailTextField: UITextField!
@IBOutlet var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func registerUser(sender: AnyObject) {
var error = ""
if usernameTextField.text == "" || emailTextField.text == "" || passwordTextField.text == "" {
error = "Please enter a username, email and password"
}
if error != "" {
var alert = UIAlertController(title: "Error In Form", message: error, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: {
action in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
} else {
var user = PFUser.currentUser()
user.username = usernameTextField.text
user.password = passwordTextField.text
user.email = emailTextField.text
user.saveInBackgroundWithBlock {
(succeeded: Bool!, signupError: NSError!) -> Void in
if signupError == nil {
println(user.username)
println(user.password)
println(user.email)
// Hooray! Let them use the app now.
} else {
//let errorString = signupError.userInfo["error"] as NSString
// Show the errorString somewhere and let the user try again.
println("Error Registering")
}
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
我很確定,如果文本字段為空,則返回nil
,而不是空字符串。 因此,只需檢查nil而不是空字符串即可解決您的問題。 更改發生在iOS 7中。請確保可以同時檢查nil和“”。 希望這可以幫助
編輯
如果您不願意,可以這樣做:
if (usernameTextField.text == nil || usernameTextField.text.length > n) || ...
其中n
是您指定的數字。 這樣,您可以確保用戶不會使用過短的用戶名或密碼進行注冊。 當然取決於您的要求。
更新:
創建user
對象時,請將其設置為PFUser.currentUser()
,因為沒有人登錄,它將為nil 。
因此,您所需要做的就是聲明var user = PFUser()
,它應該可以工作。 參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.