5秒后closuresUIAlertView

我创build了一个包含UIActivityIndi​​cator的UIAlertView。 一切都很好,但是我也想让UIAlertView在5秒后消失。

5秒后如何closures我的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() 

你可以通过编程的方式在5秒的延迟后closures你的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) }) 

Swift 3Swift 4中自动解除警报的解决scheme(部分启发: [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你可以做到这一点。 感谢@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) }) 

创build警报对象作为全局variables。 你可以使用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及更高版本中创build和pipe理警报,请使用带有UIAlertControllerStyleAlert的preferredStyle的UIAlertController。

参考: UIAlertView

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