6

我有一个用于 introViewController 的 DispatchQueue,它显示一个 gif 11 秒,然后显示我的登录页面......但也有一个按钮可以跳过介绍并显示登录。当我单击它时,时间仍在运行,当我在应用程序中导航时,时间结束时会返回登录。

这是我的课

class GifClass: UIViewController {

@IBOutlet weak var gifImage: UIImageView!
@IBOutlet weak var skipButton: UIButton!


override func viewDidLoad() {
    super.viewDidLoad()

    gifImage.loadGif(name: "promed")

    DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(11)) {

        self.performSegue(withIdentifier: "introLogin", sender: self)
    }

}


@IBAction func skip(_ sender: Any) {


    performSegue(withIdentifier: "introLogin", sender: self)

}

}

单击按钮时如何停止时间?

4

3 回答 3

35

为此,您可以使用DispatchWorkItem. 这是参考:

https://developer.apple.com/documentation/dispatch/dispatchworkitem

这是一个如何在代码中使用它的示例:

class GifClass: UIViewController {

    @IBOutlet weak var gifImage: UIImageView!
    @IBOutlet weak var skipButton: UIButton!

    private var workItem: DispatchWorkItem? // Create a private DispatchWorkItem property

    override func viewDidLoad() {
        super.viewDidLoad()

        gifImage.loadGif(name: "promed")

        workItem = DispatchWorkItem { // Set the work item with the block you want to execute
            self.performSegue(withIdentifier: "introLogin", sender: self)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(11), execute: workItem!)
    }

    @IBAction func skip(_ sender: Any) {
        workItem?.cancel() // Cancel the work item in the queue so it doesn't run
        performSegue(withIdentifier: "introLogin", sender: self)    
    } 
}
于 2017-12-29T01:28:13.967 回答
3

我不确定这里是否有最佳实践,但我会考虑使用 Timer 而不是 DispatchQueue 来做你正在做的事情。

class GifClass: UIViewController {

    @IBOutlet weak var gifImage: UIImageView!
    @IBOutlet weak var skipButton: UIButton!

    var timer = Timer()

    override func viewDidLoad() {
        super.viewDidLoad()

        gifImage.loadGif(name: "promed")

        timer = Timer.scheduledTimer(timeInterval: 11, target: self, selector: #selector(timerAction), userInfo: nil, repeats: false)
    }

    @objc func timerAction() {
        performSegue(withIdentifier: "introLogin", sender: self)
    }

    @IBAction func skip(_ sender: Any) {
        timer.invalidate()
        performSegue(withIdentifier: "introLogin", sender: self)
    }
}
于 2018-01-17T22:16:55.470 回答
1

你不停止队列。相反,当您分派的任务开始执行时,它需要检查其上下文并在上下文发生变化时做正确的事情(通常:什么都不做)。

于 2017-12-29T00:54:43.247 回答