快速 4 中的模态弹出

phi*_*ilm 1 dialog modal-dialog ios swift

我最近一直在互联网上搜索用于 iOS 编程的模态对话框的实现。

我知道 UIAlertViewController。事实上,我目前正在一个应用程序中使用这个实现。但是,我需要一些模态的东西。我需要代码停止执行,直到用户单击警报中的按钮。

到目前为止,我还没有真正看到任何令我满意的实现。这是我的代码的当前状态:

func messageBox(messageTitle: String, messageAlert: String, messageBoxStyle: UIAlertControllerStyle, alertActionStyle: UIAlertActionStyle)
    {
        var okClicked = false
        let alert = UIAlertController(title: messageTitle, message: messageAlert, preferredStyle: messageBoxStyle)

        let okAction = UIAlertAction(title: "Ok", style: alertActionStyle)
        {
            (alert: UIAlertAction!) -> Void in
            okClicked = true
        }


    /*    alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: "Default action"), style: alertActionStyle, handler: { _ in
            okClicked = true
            NSLog("The \"OK\" alert occured.")
        }))*/

        alert.addAction(okAction)

        self.present(alert, animated: true, completion: nil)
        while(!okClicked)
        {

        }
    }
Run Code Online (Sandbox Code Playgroud)

我应该考虑在故事板中创建我自己的对话框硬核风格还是 swift 有某种我可以使用的实现?

Kan*_*ire 5

如果您想要自己的辅助函数,但只想在单击确定按钮后执行代码,您应该考虑向辅助函数添加一个完成处理程序。下面是一个例子:

func messageBox(messageTitle: String, messageAlert: String, messageBoxStyle: UIAlertControllerStyle, alertActionStyle: UIAlertActionStyle, completionHandler: @escaping () -> Void)
    {
        let alert = UIAlertController(title: messageTitle, message: messageAlert, preferredStyle: messageBoxStyle)

        let okAction = UIAlertAction(title: "Ok", style: alertActionStyle) { _ in
            completionHandler() // This will only get called after okay is tapped in the alert
        }

        alert.addAction(okAction)

        present(alert, animated: true, completion: nil)
    }
Run Code Online (Sandbox Code Playgroud)

我已经从您的函数中删除了不需要的代码,并添加了一个完成处理程序作为最后一个参数。这个完成处理程序基本上是一个函数,你可以随时调用它,在这种情况下,我们在点击 OK 按钮时调用它。以下是您如何使用该功能:

viewController.messageBox(messageTitle: "Hello", messageAlert: "World", messageBoxStyle: .alert) {
    print("This is printed into the console when the okay button is tapped")
}
Run Code Online (Sandbox Code Playgroud)

() -> Void表示“一个不带参数,不返回值@escaping的函数”,表示该函数将在以后异步调用,在这种情况下,我们在点击按钮时从警报操作的处理程序中调用它。