ios - 我该怎么做:库的回调等到用户从弹出窗口中选择然后返回
问题描述
我在理解如何使用视图/委托和完成时遇到问题。
我使用具有回调的库 - 例如:func youShouldChoose()->String。
我决定给用户一个选择并打开弹出窗口。但我不明白如何返回选定的值。
我读到了完成。所以我试过这个:
func youShouldChoose() -> String {
askUser()
return self.valueForResult //This line is executed earlier than askUser is finished
}
func askUser(){
showAlert(completion: {(result)->Void in
self.valueForResult = result
})
}
func showAlert(completion:@escaping (_ result:String)->Void)
{
let alert = UIAlertController(...)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertAction.Style.default, handler: { action in
completion(textField.text)
}))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
textField.placeholder = "Enter text:"
})
self.present(alert, animated: true, completion: nil )
}
我怎样才能等到 askUser() 完全结束?有没有办法将完成的价值返回到我的图书馆?
解决方案
这是一个示例解决方案(Swift 4.2 / 5.0):
func youShouldChoose(_ completion: @escaping ((String) -> Void)) {
askUser(completion) // handing over the completion block to `askUser.
// Alternative completion block execution:
// askUser { (enteredText) in
// // This block is called when the "Click" action button on the alert was tapped.
// completion(enteredText)
// }
}
func askUser(_ completion: @escaping ((String) -> Void)) {
showAlert(completion) // handing over the completion block to `showAlert`.
}
func showAlert(_ completion: @escaping (String) -> Void) {
let alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction.init(title: "Click", style: .default, handler: { (_) in
if let textField = alert.textFields?.first, let text = textField.text {
completion(text) // -> handing over the text of the textField!
} else {
// No text field or text available. Something went wrong!
}
}))
alert.addTextField { (textField) in
textField.placeholder = "Enter text:"
}
self.present(alert, animated: true, completion: nil)
}
// How to use `youShouldChoose `:
func foo() {
youShouldChoose { (enteredText) in
// This block is called when `youShouldChoose` is finished.
print(enteredText) // -> prints the user's entered text.
print("Hello")
}
}
推荐阅读
- laravel - 部署后尝试从 aws eb 获取非对象错误的属性“id”
- r - 您如何从 API 下载数据并将其导出为漂亮的 CSV 文件以进行查询?
- r - 求解一个简单的 (?) 非线性方程组
- python - pygame:无法转发带有 .wav 扩展名的歌曲
- c - 如何计算每个线程找到 Ubuntu 的素数数量?
- javascript - 如果语句似乎无法正常工作
- javascript - 页面加载时出错,但在执行任何操作之前
- javascript - 为什么 setState 在回调中失败(使用类而不是组件)?反应原生
- c# - IL 的应用程序稳健性和安全性优势
- excel - “VBA Excel 365 Home Insider/Beta”的错误 2029 => 函数“Application.Evaluate”,带有双递归的 lambda 表达式(斐波那契)