在视图控制器之间切换时保留倒数计时器值

时间:2017-08-25 00:29:01

标签: ios swift timer viewcontroller countdown

我正在制作一个内置天气预报的旅行倒计时应用程序。

事情进展顺利,但当我从倒数计时器切换到天气预报时,再回来,倒计时器会重置。

这是我的倒计时视图控制器代码:

import UIKit

class CountdownVC: UIViewController {

    var timer = Timer()

    let userCalendar = Calendar.current
    let requestedComponent: Set<Calendar.Component> = [.day,.hour,.minute,.second]
    var departureDateTime: Date?

    @IBOutlet weak var imageView: UIImageView!

    let images = [
        UIImage(named: "MK.png")!,
        UIImage(named: "SSE1.png")!,
        UIImage(named: "TofT.png"),
        UIImage(named: "TofL1.png")!]
    var index = 0
    let animationDuration: TimeInterval = 0.25
    let switchingInterval: TimeInterval = 15

    func animateImageView()
    {
        CATransaction.begin()

        CATransaction.setAnimationDuration(animationDuration)
        CATransaction.setCompletionBlock {
            DispatchQueue.main.asyncAfter(deadline: .now() + self.switchingInterval) {
                self.animateImageView()
            }
        }

        let transition = CATransition()
        transition.type = kCATransitionFade
        imageView.layer.add(transition, forKey: kCATransition)
        imageView.image = images[index]
        imageView.contentMode = .scaleAspectFill
        imageView.alpha = 0.5

        CATransaction.commit()

        index = index < images.count - 1 ? index + 1 : 0
    }

    @IBOutlet weak var departureDateTimePicker: UIDatePicker!

    @IBAction func departureDateTimePicker(_ sender: Any) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM/dd/yy H:mm:ss"
        departureDateTimePicker.addTarget(self, action: #selector(handler), for: UIControlEvents.valueChanged)
    }


    @IBOutlet weak var selectDepartureDateTimeLabel: UILabel!
    @IBOutlet weak var daysLabel: UILabel!
    @IBOutlet weak var hoursLabel: UILabel!
    @IBOutlet weak var minutesLabel: UILabel!
    @IBOutlet weak var secondsLabel: UILabel!


    func handler(sender: UIDatePicker) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM/dd/yy H:mm:ss"
        let departureDateTimeString = dateFormatter.string(from: departureDateTimePicker.date)
        departureDateTime = dateFormatter.date(from: departureDateTimeString)
    }

    func printTime() {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM/dd/yy H:mm:ss"
        let startTime = Date()
        let endTime = departureDateTime
        let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!)
        let startTimeDouble: Double = startTime.timeIntervalSinceReferenceDate
        var endTimeDouble: Double?
        endTimeDouble = (endTime?.timeIntervalSinceReferenceDate)
        if endTimeDouble! > startTimeDouble {
            daysLabel.text = "\(timeDifference.day!) Days"
            hoursLabel.text = "\(timeDifference.hour!) Hours"
            minutesLabel.text = "\(timeDifference.minute!) Minutes"
            secondsLabel.text = "\(timeDifference.second!) Seconds"

        } else {
            timer.invalidate()
            daysLabel.text = ""
            hoursLabel.text = ""
            minutesLabel.text = ""
            secondsLabel.text = ""
        }
    }

    func runTimer() {
        let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(printTime), userInfo: nil, repeats: true)
        timer.fire()
    }

    @IBOutlet weak var startBtn: UIButton!

    @IBAction func startBtnPressed(_ sender: Any) {
        handler(sender: departureDateTimePicker)
        printTime()
        runTimer()
        selectDepartureDateTimeLabel.text = "Time to departure"
        departureDateTimePicker.isHidden = true
        startBtn.isHidden = true
    }

    @IBOutlet weak var resetBtn: UIButton!

    @IBAction func resetBtnPressed(_ sender: Any) {
        timer.invalidate()
        selectDepartureDateTimeLabel.text = "Select departure date & time"
        departureDateTimePicker.isHidden = false
        startBtn.isHidden = false
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MM/dd/yy H:mm:ss"
        let startTime = Date()
        let endTime = startTime
        let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime)
        daysLabel.text = "\(timeDifference.day!) Days"
        hoursLabel.text = "\(timeDifference.hour!) Hours"
        minutesLabel.text = "\(timeDifference.minute!) Minutes"
        secondsLabel.text = "\(timeDifference.second!) Seconds"
    }

    @IBAction func goToWeatherBtnPressed(_ sender: Any) {
        performSegue(withIdentifier: "goToWeatherVC", sender: self)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        super.viewDidLoad()
        imageView.image = images[index+1]
        animateImageView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

0 个答案:

没有答案