Home swift Find how much time has passed from the moment of clicking on...

Find how much time has passed from the moment of clicking on the

Author

Date

Category

Now I am writing a program in SWIFT and encountered such a problem, I need to find how many minutes has passed since pressing the button, I implemented it like this:

import uikit
Let Date = Date ()
Let Calendar = Calendar.Current
Class CollectingViewController: UIViewController {
  VAR Minute1: int = 0
  var minute2: int = 0
  @Ibaction Func StartButton (_ Sender: Any) {
    Minute1 = Calendar.comPonent (.minute, From: Date)
  }
  @Iboutlet Weak Var WorkedMoney: UILABEL!
  @Ibaction Func ShowMoneyButton (_ Sender: Any) {
    Minute2 = Calendar.comPonent (.minute, From: Date)
    Workedmoney.text = String (Minute2 - Minute1)
  }

I am waiting long after clicking on the first button, but always output 0, explain why? I do not understand why the second variable is not equal to that time at which I click on the second button (Minute1 for some reason is always equal to Minute2) Please explain what is not so


Answer 1, Authority 100%

This is due to the fact that you incorrectly receive the current date. You get it out of class once (in the let date = date () line) and then remove the minutes from the same date , which is stored in you in the DATE variable, And which you get not when you click on the buttons, and when starting the program.

You need to remove this line at all, and the date to be removed in each of the lines of obtaining the number of minutes, that is, these lines should look like this:

minute1 = calendar.component (.minute, from: date ())

and

minute2 = calendar.component (.minute, from: date ())


Answer 2

You can implement using Timer from the standard Foundation library.

First we make an advertisement of a timer, a variable in which the starttime timer start time will be launched, and the TimeInsec variable in which the time has passed in seconds:

Var Timer: Timer?
Var StartTime: Double!
VAR TimeInsec: Int!

At the time of clicking on the button, we call the START function which will start the timer:

func starttimer () {
  starttime = date (). TimeIntervalsIncereferencedate
  Timer = Timer.ScheduLeldtimer (TimeInterval: 0.1,
                 Target: Self,
                 SELECTOR: #Selector (Updatetimer (Timer :)),
                 UserInfo: nil,
                 REPEATS: TRUE)
}

and using the UpdateTimer function, we will record the latest timer value in the TimeInsec variable:

Func Updatetimer (Timer: Timer) {
  timeinsec = int (date (). TimeIntervalsIncereferenceDate - StartTime)
}

Now in the TimeInsec variable will be time from the start of the timer.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions