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

时间:2016-04-19 19:16:42

标签: ios swift uialertview uialertcontroller

在我的swift应用程序中,我有一个带有单个按钮的UIViewController。

此按钮调用一个函数,该函数调用3秒后消失的弹出窗口。此外,在此之后它会向控制台输出一条消息。该函数的代码如下:

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

}

这很好,但我想介绍一些改进。我想添加一个按钮,立即取消此弹出窗口,然后避免在控制台中显示该消息。有没有办法向用户显示这样的弹出窗口?另外 - 有没有一种方法可以在这个弹出消息中显示计数器的秒数,这个计数器显示弹出消失之前还剩多少时间?

3 个答案:

答案 0 :(得分:8)

您可以使用NSTimer递减计数器,更新警报视图并在计数器达到0时关闭警报视图。此代码改编自我的Objective-C answer

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

答案 1 :(得分:1)

以防万一有人需要,这是@ Paulw11解决方案的Swift 4版本

import UIKit

class ViewController: UIViewController {

    var alertController: UIAlertController?
    var alertTimer: Timer?
    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(title: "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 = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.countDown), userInfo: nil, repeats: true)

        self.present(self.alertController!, animated: true, completion: nil)
    }

    @objc func countDown() {

        self.remainingTime -= 1
        if (self.remainingTime < 0) {
            self.alertTimer?.invalidate()
            self.alertTimer = nil
            self.alertController!.dismiss(animated: 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)")
    }
}

答案 2 :(得分:0)

我知道这并不能解答您的问题,但是您是否考虑过使用MBProgressHUD SCLAlertView?它们都提供允许您显示在一段时间后消失的警报的功能。 SCLAlertView允许用户立即取消,因为MBProgressHUD没有。如果您想了解更多关于如何实现这些信息的信息,请告诉我,以便我可以添加更多信息!