首页 > 解决方案 > 我该怎么做:库的回调等到用户从弹出窗口中选择然后返回

问题描述

我在理解如何使用视图/委托和完成时遇到问题。

我使用具有回调的库 - 例如: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() 完全结束?有没有办法将完成的价值返回到我的图书馆?

标签: iosswift

解决方案


这是一个示例解决方案(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")
    }
}

推荐阅读