【问题标题】:Dismiss UIAlertView after 5 Seconds SwiftSwift 5 秒后关闭 UIAlertView
【发布时间】:2015-02-21 05:10:30
【问题描述】:

我创建了一个包含 UIActivityIndi​​cator 的 UIAlertView。一切都很好,但我也希望 UIAlertView 在 5 秒后消失。

如何在 5 秒后关闭我的 UIAlertView?

 var alert: UIAlertView = UIAlertView(title: "Loading", message: "Please wait...", delegate: nil, cancelButtonTitle: "Cancel");

 var loadingIndicator: UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(50, 10, 37, 37)) as UIActivityIndicatorView
 loadingIndicator.center = self.view.center;
 loadingIndicator.hidesWhenStopped = true
 loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
 loadingIndicator.startAnimating();

 alert.setValue(loadingIndicator, forKey: "accessoryView")
 loadingIndicator.startAnimating()

 alert.show()

【问题讨论】:

  • 如果您正在加载某些内容,为什么要在固定时间后隐藏警报?加载完成后你不想隐藏它吗?

标签: ios swift delay uialertview uiactivityindicatorview


【解决方案1】:

Swift 3Swift 4 中自动解除警报的解决方案(灵感来自这些答案的一部分:[1][2][3]) :

// the alert view
let alert = UIAlertController(title: "", message: "alert disappears after 5 seconds", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)

// change to desired number of seconds (in this case 5 seconds)
let when = DispatchTime.now() + 5
DispatchQueue.main.asyncAfter(deadline: when){
  // your code with delay
  alert.dismiss(animated: true, completion: nil)
}

结果:

【讨论】:

    【解决方案2】:

    您可以在 5 秒延迟后以编程方式关闭您的 UIAlertView,如下所示:

    alert.show()
    
    // Delay the dismissal by 5 seconds
    let delay = 5.0 * Double(NSEC_PER_SEC)
    var time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
    dispatch_after(time, dispatch_get_main_queue(), {
        alert.dismissWithClickedButtonIndex(-1, animated: true)
    })
    

    【讨论】:

    • 不需要创建第二个函数。在dispatch_after 块内只需调用alert.dismissWithClickedButtonIndex(-1, animated: true)
    • 顺便说一句 - 我更喜欢这种方法而不是使用计时器。
    • @rmaddy 它更灵活,但更丑陋。我明白为什么人们会仅仅出于审美原因而避免使用它。
    【解决方案3】:

    在 swift 2 中你可以做到这一点。感谢@Lyndsey Scott

     let alertController = UIAlertController(title: "youTitle", message: "YourMessage", preferredStyle: .Alert)
                    self.presentViewController(alertController, animated: true, completion: nil)
                    let delay = 5.0 * Double(NSEC_PER_SEC)
                    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
                    dispatch_after(time, dispatch_get_main_queue(), {
                        alertController.dismissViewControllerAnimated(true, completion: nil)
                    })
    

    【讨论】:

    • 如果警报上有一个确定按钮并且用户在调度执行之前单击它会发生什么?
    • 我想知道它是否会崩溃,因为如果用户在 5 秒延迟之前按下 ok 按钮,alertControler 已经关闭。我试过了,我没有收到任何错误消息。所以我想没关系。
    • 在 Android 上,我制作了一个自动关闭消息框,用倒计时 OK (5), OK(4), ....OK(1) 更新 ok 按钮标题。我非常想做类似的事情,但我认为我不能使用 alertController。
    【解决方案4】:

    对于 swift 4,您可以使用此代码

    let alertController = UIAlertController(title:"Alert",message:nil,preferredStyle:.alert)
    self.present(alertController,animated:true,completion:{Timer.scheduledTimer(withTimeInterval: 5, repeats:false, block: {_ in
        self.dismiss(animated: true, completion: nil)
    })})
    

    【讨论】:

      【解决方案5】:

      将警报对象创建为全局变量。 为此,您可以使用NSTimer

      var timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("dismissAlert"), userInfo: nil, repeats: false)
      
      
      func dismissAlert()
      {
          // Dismiss the alert from here
          alertView.dismissWithClickedButtonIndex(0, animated: true)
      
      }
      

      注意:

      重要提示:UIAlertView 在 iOS 8 中已弃用。(请注意 UIAlertViewDelegate 也已弃用。)创建和管理警报 在 iOS 8 及更高版本中,使用 UIAlertController 和 UIAlertControllerStyleAlert 的首选样式。

      参考:UIAlertView

      【讨论】:

        【解决方案6】:

        对于 Swift 3

        let alert = UIAlertController(title: “Alert”, message: “Message”,preferredStyle: UIAlertControllerStyle.alert)
        self.present(alert, animated: true, completion: nil)
         DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double((Int64)(5.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: {() -> Void in
             alert.dismiss(animated: true, completion: {() -> Void in
         })
        })
        

        【讨论】:

          【解决方案7】:

          @ronatory 在 c# 中的回答

          var when = new DispatchTime(DispatchTime.Now, 
          TimeSpan.FromSeconds(5));
          DispatchQueue.MainQueue.DispatchAfter(when, () =>
          {
              // your code with delay
              alertController.DismissModalViewController(true);
          });
          

          【讨论】:

            【解决方案8】:

            iOS 8.0+ 中,UIAlertController 继承自 UIViewController,所以,它就是一个视图控制器。因此,所有限制都适用。这就是为什么当视图有可能被用户关闭时,在没有适当检查的情况下尝试关闭它并不完全安全。

            在下面的 sn-p 中有一个如何实现的示例。

            func showAutoDismissableAlert(
                  title: String?,
                  message: String?,
                  actions: [MyActionWithPayload], //This is just an struct holding the style, name and the action in case of the user selects that option
                  timeout: DispatchTimeInterval?) {
            
              let alertView = UIAlertController(
                  title: title,
                  message: message,
                  preferredStyle: .alert
              )
            
              //map and assign your actions from MyActionWithPayload to alert UIAlertAction
              //(..)
            
              //Present your alert
              //(Here I'm counting on having the following variables passed as arguments, for a safer way to do this, see https://github.com/agilityvision/FFGlobalAlertController) 
              alertView.present(viewController, animated: animated, completion: completion)
            
            
              //If a timeout was set, prepare your code to dismiss the alert if it was not dismissed yet
              if let timeout = timeout {
                DispatchQueue.main.asyncAfter(
                   deadline: DispatchTime.now() + timeout,
                   execute: { [weak alertView] in
                        if let alertView = alertView, !alertView.isBeingDismissed {
                            alertView.dismiss(animated: true, completion: nil)
                        }
                    }
                }
            }
            

            【讨论】:

              【解决方案9】:

              //关闭警报 w.r.t 定时器的通用函数

              /** showWithTimer */
              public func showWithTimer(message : String?, viewController : UIViewController?) {
              
                  let version : NSString = UIDevice.current.systemVersion as NSString
                  if  version.doubleValue >= 8 {
                      alert = UIAlertController(title: "", message: message, preferredStyle:.alert)
                      viewController?.present(alert ?? UIAlertController(), animated:true, completion:nil)
                      let when = DispatchTime.now() + 5
                      DispatchQueue.main.asyncAfter(deadline: when){
                          self.alert?.dismiss(animated: true, completion: nil)
                      }
                  }
              }
              

              【讨论】:

                【解决方案10】:

                我不是专家,但这对我有用,我想更容易

                let alert = UIAlertController(title: "", message: "YOUR MESSAGE", preferredStyle: .alert)
                present(alert, animated: true) {
                   sleep(5)
                   alert.dismiss(animated: true)
                }
                

                【讨论】:

                  猜你喜欢
                  • 2013-01-04
                  • 1970-01-01
                  • 2015-03-29
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-10-02
                  • 1970-01-01
                  • 2015-02-21
                  • 1970-01-01
                  相关资源
                  最近更新 更多