ios Swift 5 秒后关闭 UIAlertView
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27613926/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dismiss UIAlertView after 5 Seconds Swift
提问by Serge Pedroza
I've created a UIAlertView that contains a UIActivityIndicator. Everything works great, but I'd also like the UIAlertView to disappear after 5 seconds.
我创建了一个包含 UIActivityIndicator 的 UIAlertView。一切正常,但我也希望 UIAlertView 在 5 秒后消失。
How can I Dismiss my UIAlertView after 5 seconds?
如何在 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()
回答by ronatory
A solution to dismiss an alert automatically in Swift 3and Swift 4(Inspired by part of these answers: [1], [2], [3]):
在Swift 3和Swift 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)
}
Result:
结果:
回答by Lyndsey Scott
You can dismiss your UIAlertView
after a 5 second delay programmatically, like so:
您可以UIAlertView
在 5 秒延迟后以编程方式关闭,如下所示:
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)
})
回答by George Asda
in swift 2 you can do this. Credit to @Lyndsey Scott
在 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)
})
回答by Vaishnavi
For swift 4 you can use this code
对于 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)
})}
回答by Midhun MP
Create the alert object as a global variable.
You can use a NSTimer
for this purpose.
将警报对象创建为全局变量。您可以NSTimer
为此目的使用 a 。
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)
}
NOTE:
笔记:
Important: UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is also deprecated.) To create and manage alerts in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert.
重要提示:UIAlertView 在 iOS 8 中已弃用。(注意 UIAlertViewDelegate 也已弃用。)要在 iOS 8 及更高版本中创建和管理警报,请改用 UIAlertController 和首选样式 UIAlertControllerStyleAlert。
Reference : UIAlertView
参考:UIAlertView
回答by Yakup Ad
For Swift 3
对于 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
})
})
回答by Pratyush Pratik
//Generic Function For Dismissing alert w.r.t Timer
//用于解除警报wrt定时器的通用函数
/** 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)
}
}
}
回答by user8016538
I'm not an expert but this works for me and I guess is easier
我不是专家,但这对我有用,我想更容易
let alert = UIAlertController(title: "", message: "YOUR MESSAGE", preferredStyle: .alert)
present(alert, animated: true) {
sleep(5)
alert.dismiss(animated: true)
}
回答by jtth
@ronatory 's answer in c#
@ronatory 在 C# 中的回答
var when = new DispatchTime(DispatchTime.Now,
TimeSpan.FromSeconds(5));
DispatchQueue.MainQueue.DispatchAfter(when, () =>
{
// your code with delay
alertController.DismissModalViewController(true);
});
回答by Hugo Alonso
In iOS 8.0+UIAlertController
inherits from UIViewController
, so, it is just that, a view controller. So, all the restrictions apply. That's why when there's a possibility that the view gets dismissed by the user, it's not entirely safe to try to dismiss it without proper checks.
在iOS 8.0+ 中UIAlertController
继承自UIViewController
,所以,它只是一个视图控制器。因此,所有限制都适用。这就是为什么当视图有可能被用户关闭时,在没有适当检查的情况下尝试关闭它并不完全安全。
In the following snippet there's an example of how this can be achieved.
在以下代码段中,有一个示例说明如何实现这一点。
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)
}
}
}
}