将文本从UIAlertController返回到扩展

时间:2019-04-11 22:26:23

标签: ios swift uialertcontroller

在Swift中,如何返回写入UIAlertController的文本字段中的字符串,如果此UIAlertController位于扩展内

通常,如果将UIAlertController实现放在本地类中,则可以轻松地传递文本,但是当警报进入扩展时,我不确定哪种方法可以返回文本。

例如,假设您具有此扩展名:

extension UIViewController {
    func presentTextFieldAlert(title: String, message: String, textFieldPlaceholder: String ) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let saveAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { _ -> Void in
            let urlTextField = alertController.textFields![0] as UITextField
            if urlTextField.text != nil { }
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .default)
        alertController.addTextField { (textField: UITextField!) -> Void in
            textField.placeholder = textFieldPlaceholder
        }
        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
}

进入您的班级:

class Client: UIViewController {

    func showAlert() {
        self.presentTextFieldAlert(title: "Hello", message: "Write sth", textFieldPlaceholder: "Write here")
    }
}

如何将警报中的文本传递给ViewController?

我尝试过类似的事情:

class Client: UIViewController {

    func showAlert() -> String {
        return self.presentTextFieldAlert(title: "Hello", message: "Write sth", textFieldPlaceholder: "Write here")
    }
}

但是我认为这不是正确的方法。

1 个答案:

答案 0 :(得分:3)

使用完成处理程序。

$start_date = "2017-05-17";

while ($start_date != "2019-04-12") {

    $sql_select = "SELECT * 
                    FROM table 
                    WHERE DATE(FROM_UNIXTIME(timestamp)) = '$start_date'";

    $result_select = $GLOBALS['db']->query($sql_select);
    while ($row = $result_select->fetch_array()) {
        // will do stuff here
    }
    $start_date = date("Y-m-d", strtotime($start_date. "+1 day"));
}

然后您可以将其用作:

extension UIViewController {
    func presentTextFieldAlert(title: String, message: String, textFieldPlaceholder: String, completion: @escaping (String?)->()) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let saveAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { _ -> Void in
            let urlTextField = alertController.textFields![0] as UITextField
            completion(urlTextField.text)
        }

        let cancelAction = UIAlertAction(title: "Cancel", style: .default)
        alertController.addTextField { (textField: UITextField!) -> Void in
            textField.placeholder = textFieldPlaceholder
            completion(nil)
        }
        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
}