Swift 4倒数计时器NowDate - 日期

时间:2018-03-07 14:56:29

标签: swift xcode

我想在2018年6月2日制作一个倒数计时器。我该怎么办呢。当用户打开应用程序时,它应该从中断处继续。

我解决了这段代码。其他人正在寻找相同的代码。我看到有人对Stack Overflow有所帮助,我完成了它。

class ViewController: UIViewController {

@IBOutlet weak var ayLabel: UILabel!
@IBOutlet weak var gunLabel: UILabel!
@IBOutlet weak var saatLabel: UILabel!
@IBOutlet weak var dakikaLabel: UILabel!
@IBOutlet weak var saniyeLabel: UILabel!
@IBOutlet weak var secimGunu: UILabel!

let formatter = DateFormatter()
let userCleander = Calendar.current;
let requestedComponent : Set<Calendar.Component> = [
    Calendar.Component.month,
    Calendar.Component.day,
    Calendar.Component.hour,
    Calendar.Component.minute,
    Calendar.Component.second
]

override func viewDidLoad() {
    super.viewDidLoad()


    let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timePrinter), userInfo: nil, repeats: true)

    timer.fire()

}

func timeCalculator(dateFormat: String, endTime: String, startTime: Date = Date()) -> DateComponents {
    formatter.dateFormat = dateFormat
    let _startTime = startTime
    let _endTime = formatter.date(from: endTime)

    let timeDifference = userCleander.dateComponents(requestedComponent, from: _startTime, to: _endTime!)
    return timeDifference
}

@objc func timePrinter() -> Void {
   let time = timeCalculator(dateFormat: "dd/MM/yyyy HH:mm:ss a", endTime: "02/06/2018 00:00:00 a")
    ayLabel.text = "\(time.month!)"
    gunLabel.text = "\(time.day!)"
    saatLabel.text = "\(time.hour!)"
    dakikaLabel.text = "\(time.minute!)"
    saniyeLabel.text = "\(time.second!)"

}

1 个答案:

答案 0 :(得分:-2)

  1. 由于问题非常广泛,最简单的解决方案是使用众多网络服务中的一个来显示倒计时,并将其保存为Safari主页的快捷方式(分享 - >添加到主屏幕)。像这样:
  2. https://www.timeanddate.com/countdown/generic?iso=20180602T02&p0=136&font=cursive

    1. 如果你真的想要一个应用程序,无论出于何种原因,最简单的选择是让一个视图应用程序在Web视图中打开上面的URL。

    2. 如果您绝对需要编写自己的原生应用。然后,您需要在Xcode中创建一个视图应用程序,并在其视图中使用标签,并在其ViewController中每隔一秒(或您想要的任何时间段)触发计时器。计时器触发的事件会减少标签(或者您想要显示剩余时间)。应用程序还需要处理恢复(可能通过注册到UIApplicationDidBecomeActiveNotification)以确保从后台恢复时剩余时间得到更新。

相关问题