ios - 如何在 Swift 中显示 3 秒后消失或可由用户立即取消的弹出消息?

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

}

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

最佳答案

您可以使用 NSTimer 来递减计数器,更新警报 View 并在计数器达到 0 时关闭警报 View 。此代码改编 self 的 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)")
    }     
}

关于ios - 如何在 Swift 中显示 3 秒后消失或可由用户立即取消的弹出消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36727474/

相关文章:

ios - 根据条件更新约束

iOS7 崩溃 - [__NSPlaceholderDictionary initWithObjects

swift - Vapor 项目不使用 Swift 4 和 Xcode 9 构建/运行

iphone - 在 ios 5.0 中显示带有 Textfield 的警报 View 时键盘无法打开

swift - 为什么我的警报 View Controller 不工作

ios - 如何以编程方式创建固定空间和灵活的空格键按钮项?

ios - 禁用 NSFetchedResultsController 在批量更新删除时生成的动画

swift - 在 Swift 2.1 中将多个选项传递给 NSLineBreakMode

ios - 核心数据 : load data in background and save

iphone - 在 UIAlertView 中使用 slider ?