Swift学习笔记(九):GCD定时器+切换rootViewController+过渡效果

85 阅读1分钟

GCD定时器+切换rootViewController+过渡效果

class AdvertiseViewController: BaseViewController {

    

    @IBOutlet weak var titleLabel: UILabel!

    // 延迟初始化 timer

    lazy var timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.global())

    // 倒计时的时间

    var seconds = 5

  


    override func viewDidLoad() {

        super.viewDidLoad()

        

        myNaviBar.isHidden = true

        view.backgroundColor = .systemIndigo

        titleLabel.text = "哈哈哈哈"

        timeCountDown()

    }

    

    func timeCountDown() {

        timer.schedule(deadline: .now(), repeating: .seconds(1))

        timer.setEventHandler(handler: {

            DispatchQueue.main.async { [weak self] in

                if self!.seconds <= 0 {

                    self!.terminer()

                }

                self!.seconds -= 1

            }

        })

        timer.resume()

    }

    

    func terminer() {

        timer.cancel()

        switchRootController()

    }

    

    func switchRootController() {

        let window = UIApplication.shared.windows.first!

        // 过渡动画:0.5s 淡出

        UIView.transition(with: window,

                          duration: 0.5,

                          options: .transitionCrossDissolve,

                          animations: {

                            let old = UIView.areAnimationsEnabled

                            UIView.setAnimationsEnabled(false)

                            window.rootViewController = MainTabBarController()

                            UIView.setAnimationsEnabled(old)

                          }, completion: { _ in

                            // Do Nothing

                          })

    }

  


}