我无法理解如何使用 View /委托(delegate)和完成。
我使用具有回调的库 - 例如: 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() 完全结束?有没有办法将完成后的值返回到我的库中?
最佳答案
我找到了两种方法来解决这个问题: 1.使用循环。显示 View 直到标志为 false
askUser() //we should set flag to true here
while( flag == false ) {
CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 1, true);
}
return self.valueForResult
使用信号量
let semaphore = DispatchSemaphore(value: 0) askUser() semaphore.lock() return self.valueForResult
关于ios - 我该怎么做 : library's callback wait until user choose from popover and then get return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57453390/