如何在Xcode中使用Swift代码

时间:2018-01-09 17:09:51

标签: ios xcode

我遇到了问题。我是iOS编程的新手,我很难理解Swift代码是如何被激活的。例如,在下面的代码段中,我认为每一行都是在上面的代码之后执行的。但是当它到达 passData()函数时,它不会执行该功能。它继续前进,并且一段时间后(或更早)它使它(passData函数)更好。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if numLaunches == 0{
        nombre = usuario()
        numLaunches += 1
    }
}
func usuario() -> String {
    var tField: UITextField!

    func configurationTextField(textField: UITextField!)
    {
        print("generating the TextField")
        textField.placeholder = "Enter an item"
        textField.textAlignment = .center
        tField = textField
    }

    func handleCancel(alertView: UIAlertAction!)
    {
        print("Cancelled !!")
    }

    let alert = UIAlertController(title: "Please Enter Your Name", message: "", preferredStyle: .alert)

    alert.addTextField(configurationHandler: configurationTextField)
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:handleCancel))
    alert.addAction(UIAlertAction(title: "Done", style: .default, handler:{ (UIAlertAction) in
        print("Done !!")

        print("Item : \(String(describing: tField.text))")
        self.nombre = tField.text!
    }))
    self.present(alert, animated: true, completion: {
        print("completion block")
    })
    print(self.nombre)
    passData()
    if tField.text == nil {
        return "No value"
    }else{
        return (tField.text!)
    }
}

func passData() {
    let myVC = storyboard?.instantiateViewController(withIdentifier: "SecondVC") as! AboutViewController
    if myVC.playerName != nil {
        myVC.playerName.text = nombre
    }else{

    }
    navigationController?.pushViewController(myVC, animated: true)
    print("pasa el dato")
}

所以,问题是,我需要将变量“ nombre ”的内容传递给另一个VC。但是当passData函数被驱逐时该变量为空。我想如果我在变量更新后调用了该函数,它将传递正确的内容。但我明显错了。

我很感激帮助!

1 个答案:

答案 0 :(得分:1)

一般情况下,除非您的函数是异步的,否则您理解代码是从上到下执行是正确的。在这种情况下,我认为您只是对您的UIAlertAction代码感到困惑。您似乎向用户弹出警报,要求他们写下他们的姓名,当他们点击“完成”时,您想要调用passData()功能。在这种情况下,您应该将passData()电话置于<{1}}内,如下所示:

UIAlertAction

在用户按下该按钮之前,alert.addAction(UIAlertAction(title: "Done", style: .default, handler:{ (UIAlertAction) in print("Done !!") print("Item : \(String(describing: tField.text))") self.nombre = tField.text! self.passData() })) 的处理程序内的代码将不会执行,这就是为什么您发现UIAlertAction过早被调用的原因。