如何在Swift中显示popup消息3秒钟后消失或者立即可以被用户取消?

在我的swift应用程序,我有一个单一的buttonUIViewController。

这个button调用一个函数,调用3秒钟后消失的popup窗口。 此外,在那之后,它将打印一条消息给控制台。 这个函数的代码如下:

func showAlertMsg(title: String, message: String){ let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) self.presentViewController(alertController, animated: true, completion: nil) let delay = 3.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) print("popup disappeared") }) } 

这工作正常,但我想介绍一些改进。 我想添加一个button,将立即取消这个popup,然后避免在控制台显示消息。 有没有办法向用户显示这样的popup窗口? 另外 – 是否有方法显示在这个popup消息的计数器秒数运行,显示多less时间,直到popup消失?

您可以使用NSTimer递减计数器,更新警报视图并在计数器达到0时closures警报视图。此代码是从我的Objective-C答案

 class ViewController: UIViewController { var alertController: UIAlertController? var alertTimer: NSTimer? var remainingTime = 0 var baseMessage: String? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.showAlertMsg("Test Alert", message: "This will disappear in ", time: 5) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func showAlertMsg(title: String, message: String, time: Int) { guard (self.alertController == nil) else { print("Alert already displayed") return } self.baseMessage = message self.remainingTime = time self.alertController = UIAlertController(title: title, message: self.alertMessage(), preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in print("Alert was cancelled") self.alertController=nil; self.alertTimer?.invalidate() self.alertTimer=nil } self.alertController!.addAction(cancelAction) self.alertTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(ViewController.countDown), userInfo: nil, repeats: true) self.presentViewController(self.alertController!, animated: true, completion: nil) } func countDown() { self.remainingTime -= 1 if (self.remainingTime < 0) { self.alertTimer?.invalidate() self.alertTimer = nil self.alertController!.dismissViewControllerAnimated(true, completion: { self.alertController = nil }) } else { self.alertController!.message = self.alertMessage() } } func alertMessage() -> String { var message="" if let baseMessage=self.baseMessage { message=baseMessage+" " } return(message+"\(self.remainingTime)") } } 

我知道这直接不回答你的问题,但你有没有考虑使用MBProgressHUD SCLAlertView ? 它们都提供了一些function,可以让您显示一段时间后消失的警报。 SCLAlertView允许用户立即取消MBProgressHUD的位置。 如果你想了解如何实现这些的更多信息,让我知道,所以我可以添加更多的信息!