代码之家  ›  专栏  ›  技术社区  ›  philm

swift 4中的模式弹出窗口

  •  1
  • philm  · 技术社区  · 7 年前

    我最近在互联网上搜索iOS编程模式对话框的实现。

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

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

    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)
            {
    
            }
        }
    

    我是否应该在情节提要中创建自己的对话框核心样式,或者swift是否有某种我可以使用的实现?

    2 回复  |  直到 7 年前
        1
  •  5
  •   Kane Cheshire    7 年前

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

    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)
        }
    

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

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

    () -> Void 表示“不带参数、不返回值的函数”,以及 @escaping 意味着该函数将在稍后的日期异步调用,在本例中,我们将在点击按钮时从警报操作的处理程序调用它。

        2
  •  0
  •   kcg94    7 年前
    // declare an alert 
    let alert = UIAlertController(title: <#Your Title#>, message:  <#Your Message#> preferredStyle: UIAlertControllerStyle.actionSheet)
    //create action and add them to alert
    let actionX = UIAlertAction(title:  <#Your Title#>, style: UIAlertActionStyle.default, handler: {(action) in
         // do whatever you want  
    }))
    alert.addAction(actionX)
    

    您应该查看闭包,以了解如何在swift中轻松编写代码