【问题标题】:Passing error with "perform segue" returns nil?使用“执行segue”传递错误返回nil?
【发布时间】:2020-05-24 19:05:02
【问题描述】:

我试图在应用程序用户以错误的方式登录或注册时向他们显示错误,例如密码需要 6 个字符,所以如果他/她输入 4 或 5,它应该会给他带来错误,但它只会在 Xcode 中打印并且在应用程序中始终为零(我是新来的,网站告诉我图片太大而无法上传,所以我会写下来)。有人可以帮我弄清楚这里的代码有什么问题吗?谢谢!!

// This is the code for the first viewcontroller where I try to pass the error to the ErrorViewController

 if let email = emailTextfield.text, let password = passwordTextfield.text{
    Auth.auth().signIn(withEmail: email, password: password) { [weak self] authResult, error in 
     if let e = error {
        print(e)
        self!.performSegue(withIdentifier: "GoToError", sender: self)
       func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       if segue.identifier == "GoToError" {
           let GoTo = segue.destination as! ErrorViewController
        GoTo.errorText = "\(e.localizedDescription)"}
       }
     }else{
        self!.performSegue(withIdentifier:K.loginSegue, sender: self)
        }

    }
    }

// This is the code of the ErrorViewController where It should catch the error and pass it to the ErrorText label and get printed to the app screen 

errorText: String?   

@IBOutlet weak var ViewMessage: UIView!
@IBOutlet weak var ErrorText: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()

     ViewMessage.layer.cornerRadius = ViewMessage.frame.size.height / 4



    if errorText != nil {
    ErrorText.text = errorText
    }else{

// The string below is what gets printed because the error is always nil

        ErrorText.text = "make sure your password is at least 6 characters"

【问题讨论】:

    标签: ios swift xcode error-handling segue


    【解决方案1】:

    原因是prepare(for segue必须在类的顶层实现(与viewDidLoad同级)。

    请以小写字母开头的变量、函数和枚举案例命名。

    【讨论】:

      【解决方案2】:
      func prepare(for segue: UIStoryboardSegue, sender: Any?)
      

      每次 segue 发生时都会调用此函数(当 performSegue(withIndentifier:sender) 函数调用时)。

      viewController 无法访问 prepare() 函数,因为它在 if/else 块的本地范围内。

      更具体地说,prepare(for segue) 函数仅存在于 if/else 块的范围内,即包装在闭包中,即包装在另一个 if/else 块中。

      但是这个函数应该总是可以被 viewController 访问,这就是为什么它应该被放置在顶级范围内。

      这样

      class MyViewController: UIViewController {
      
          //other class properties and methods
      
          override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
              //your code here
          }
      }
      

      我建议在 swift 中阅读有关范围和上下文的更多信息。

      【讨论】:

        猜你喜欢
        • 2016-12-20
        • 1970-01-01
        • 2016-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-13
        • 2011-04-07
        相关资源
        最近更新 更多