gpt4 book ai didi

swift - 从警告框中获取文本值

转载 作者:搜寻专家 更新时间:2023-11-01 06:06:20 28 4
gpt4 key购买 nike

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

@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

}

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

最佳答案

您的 ok 操作处理程序(闭​​包)将在您单击 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.

}
}

关于swift - 从警告框中获取文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36315068/

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