我创建了一个包含UIActivityIndicator的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()
你可以通过编程方式延迟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)
})
在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)
}
}
}
}
在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)
}
结果:
在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)
})
将警报对象创建为全局变量。你可以使用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)
}
注意:
重要提示:在iOS 8中不推荐使用UIAlertView。(请注意,UIAlertViewDelegate也已弃用。)要在iOS 8及更高版本中创建和管理警报,请使用UIAlertController,其优先级为UIAlertControllerStyleAlert。
参考:UIAlertView
对于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)
})}
对于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
})
})
我不是专家,但这适合我,我想更容易
let alert = UIAlertController(title: "", message: "YOUR MESSAGE", preferredStyle: .alert)
present(alert, animated: true) {
sleep(5)
alert.dismiss(animated: true)
}
//用于解除警报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)
}
}
}
@ronatory在c#中的答案
var when = new DispatchTime(DispatchTime.Now,
TimeSpan.FromSeconds(5));
DispatchQueue.MainQueue.DispatchAfter(when, () =>
{
// your code with delay
alertController.DismissModalViewController(true);
});