从警告框

时间:2016-03-30 16:52:33

标签: swift alert

我在从UIAlertController获取文本字段值时遇到问题。我得到了值,但似乎是以错误的顺序执行我的代码。在下面的函数中,我希望函数调用返回一个字符串,但是在函数返回时没有设置该值。

@IBAction func btnSaveSession(sender: AnyObject) {

    //Prompt user to enter session name

    var sessionName: String = ""

    sessionName = promptUserToEnterSessionName("Save Session", message: "Please enter the name of your custom session below.");

    print("session Name: " + sessionName)

    //Save session to firebase.

    //redirect to create session controller.
}

func promptUserToEnterSessionName(title: String, message: String) -> String{

    var sessionName: String = ""

    //1. Create the alert controller.
    let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)

    //2. Add the text field. You can configure it however you need.
    alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
        textField.text = "Enter session name."
    })

    //3. Grab the value from the text field, and print it when the user clicks OK.
    alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
        let textField = alert.textFields![0] as UITextField
        print("Text field: \(textField.text)")
        sessionName = textField.text!
    }))

    // 4. Present the alert.
    self.presentViewController(alert, animated: true, completion: nil)

    return sessionName

}

如果有人在理解我的问题时遇到问题,请发表评论,我会尽力解释。

3 个答案:

答案 0 :(得分:4)

单击确定按钮时, ok操作处理程序(闭​​包)将调用。因此,不要将值赋给局部变量sessionName,而是在类中创建一个sessionName变量。

class YourClass {
var sessionName: String?

...

@IBAction func btnSaveSession(sender: AnyObject) {

//Prompt user to enter session name

promptUserToEnterSessionName("Save Session", message: "Please enter the name of your custom session below.");

}


func promptUserToEnterSessionName(title: String, message: String) {


//1. Create the alert controller.
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Enter session name."
})

//3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    print("Text field: \(textField.text)")
    self.sessionName = textField.text!
    self.testDemo()
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)


}

fun TestDemo() {
print("session Name: " + self.sessionName)

//Save session to firebase.

//redirect to create session controller.

}
 }

答案 1 :(得分:1)

您可以使用Callback来获取值,如下所示:

func AlertPrompt(vista:UIViewController, titulo:String , mensaje:String, aceptar:String, completion: @escaping (_ resultado: String)->()) {
        let miAlerta = UIAlertController(title: titulo, message: mensaje, preferredStyle: UIAlertControllerStyle.alert)
        miAlerta.addTextField(configurationHandler: {
            (textField) -> Void in
        })
        let okBoton = UIAlertAction(title: aceptar, style: UIAlertActionStyle.default, handler: {
            (action) -> Void in
            let result = miAlerta.textFields![0] as UITextField
            // You return the value here
            completion(result.text! as String)
        })
        miAlerta.addAction(okBoton)
        let cancelBoton = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)
        miAlerta.addAction(cancelBoton)
        vista.present(miAlerta, animated: true, completion: nil)
}

并调用这样的函数:

AlertPrompt(vista: self, titulo: "Title", mensaje: "some message", aceptar: "Acept"){(resultado)->() in
     print(resultado)
}

这对我来说非常合适,希望得到这个帮助

答案 2 :(得分:0)

此代码:

let textField = alert.textFields![0] as UITextField
print("Text field: \(textField.text)")
sessionName = textField.text!
只有在单击与定义的操作对应的按钮时才会调用

。所以在创建UIAlertController的那一刻它没有被调用。

阅读Swift中的块,它应该更加清晰。