在5秒Swift之后解散UIAlertView

时间:2014-12-23 04:05:19

标签: ios swift delay uialertview uiactivityindicatorview

我创建了一个包含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()

10 个答案:

答案 0 :(得分:70)

Swift 3 Swift 4 中自动解除警报的解决方案(受部分答案启发:[1][2][3]):

x

<强>结果:

enter image description here

答案 1 :(得分:40)

您可以通过编程方式延迟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)
})

答案 2 :(得分:13)

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

答案 3 :(得分:6)

将警报对象创建为全局变量。 您可以使用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的preferredStyle。

参考:UIAlertView

答案 4 :(得分: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 :(得分:1)

  

适用于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
 })
})

答案 6 :(得分:1)

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

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

答案 7 :(得分:0)

//用于解除警报的通用函数w.r.t Timer

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

答案 8 :(得分:0)

@ronatory在c#中的答案

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

答案 9 :(得分:0)

iOS 8.0 + 中,UIAlertController继承自UIViewController,因此,就是一个视图控制器。因此,所有限制都适用。这就是为什么当用户有可能关闭视图时,尝试未经适当检查将其关闭并不完全安全的原因。

在下面的代码片段中,有一个如何实现此目标的示例。

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