gpt4 book ai didi

swift - if 语句执行自己而不是其他人

转载 作者:行者123 更新时间:2023-11-28 05:54:55 25 4
gpt4 key购买 nike

我这里有一个代码,每次运行它时,只有声明“所有字段都是必需的”的 if 语句有效,但不仅在必须调用它时,它实际上会代替其他语句运行。因此,即使所有字段都已完成,无论我做什么,我都会收到“所有字段都需要”作为警告消息。这是代码,感谢所有帮助,在此先感谢您。

import UIKit

class RegisterPageViewController: UIViewController {


@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
@IBOutlet weak var repeatPasswordTextField: 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 registerButtonTapped(_ sender: AnyObject) {

let userEmail = ""
let userPassword = ""
let userRepeatPassword = ""



// Check for empty fields


if (userEmail.isEmpty || userPassword.isEmpty ||
userRepeatPassword.isEmpty)
{
// Display Alert Message
displayMyAlertMessage(userMessage:"All fields are required")
return
}

//Check if passwords match
if (userPassword != userRepeatPassword)
{
// Display an alert message
displayMyAlertMessage(userMessage:"Passwords do not match")
return
}


// Store data
UserDefaults.standard.set(userEmail, forKey:"userEmail")
UserDefaults.standard.set(userEmail, forKey:"userPassword")
UserDefaults.standard.synchronize()


// Display alert message with confirmation
_ = UIAlertController(title:"Alert", message:"Registration is
successfull. Thank you!",
preferredStyle:UIAlertControllerStyle.alert);

_ = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default)
{
action in
self.dismiss(animated: true, completion:nil)
}



}


func displayMyAlertMessage(userMessage:String)
{

let myAlert = UIAlertController(title:"Alert", message: userMessage,
preferredStyle:UIAlertControllerStyle.alert);


let okAction = UIAlertAction(title:"Ok",
style:UIAlertActionStyle.default, handler:nil)

myAlert.addAction(okAction)

self.present(myAlert, animated:true, completion:nil)


}


}

最佳答案

您是否曾为 userEmail、userPassword、userRepeatPassword 分配任何值?您在函数开始时将它们初始化为空,看起来它们的值永远不会改变。

与其在函数中声明它们,不如尝试使用类级变量,并将它们链接到 Storyboard 中的文本字段。

@IBOutlet weak var userEmail: UITextField!
@IBOutlet weak var userPassword: UITextField!
@IBOutlet weak var userRepeatPassword: UITextField!

@IBAction func registerButtonTapped(_ sender: AnyObject) {
// Check for empty fields
if (self.userEmail.text.isEmpty || self.userPassword.text.isEmpty || self.userRepeatPassword.text.isEmpty) {
// Display Alert Message
displayMyAlertMessage(userMessage:"All fields are required")
return
}
...
}

关于swift - if 语句执行自己而不是其他人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51717278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com