简体   繁体   中英

timer not show correct time when press button swiftUI

I'm creating a timer app, where in the screen where I set the timer with the buttons I would like to change the string displayed. in this case if I press the "10" second button twice, I only see 10sec and not 20sec.

How can I manage several buttons of different times that are added together? I made this model, but I think it is completely incorrect and I don't know how to handle it.

        @ObservedObject var tm: TimeManager
    
    var body: some View {
        VStack {
            ContdownView(text:tm.timerap, bgColor: .yellow)
                .cornerRadius(16)
                .padding()
                .shadow(radius: 2)
            
            VStack{
                Button(action: { self.tm.start() }) {
                    ButtonView(text: "10 SEC", bgColor: .red)
                        .cornerRadius(16)
                        .padding(.leading, 16)
                }
                Button(action: { self.tm.stop() }) {
                    ButtonView(text: "STOP", bgColor: .red)
                        .cornerRadius(16)
                        .padding(.leading, 16)
                }
            }
        }
    }


class TimeManager:ObservableObject {
        
    var timer = Timer()
        
    var timerap: String = "00:00:00" {
        didSet {
            self.objectWillChange.send()
        }
    }
    
    func start() {
        if !timer.isValid {
            timer = Timer.scheduledTimer(withTimeInterval: 0.0,
                                         repeats: false) { timer in
                self.tick()
            }
        }
    }
    
    func tick() {
        /// aumentiamo il contatore
        timerap = "00:00:10"
    }
    
    func stop() {
        if timer.isValid {
            timer.invalidate()
        } else {
            contatore = 0
            timerap = "00:00:00"
        }
    }
    
    func pausa() {
        if timer.isValid {
            timer.invalidate()
        }
    }
    
    func timeString(_ time:TimeInterval) -> String {
        let hours = Int(time) / 3600
        let minutes = Int(time) / 60
        let seconds = time - Double(minutes) * 60
        return String(format:"%02i:%02i:%02i",hours,minutes,Int(seconds))
    }
}

You should add seconds each time, but you are just trying to create your timer object every time.

Here is a good example for you. You can start here and refactor it depending on your requests.

import SwiftUI

struct ContentView: View {
    @State var isCounting = false
    @State var remainingSeconds = 10
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    
    var body: some View {
        VStack {
            Text("\(timeString(from: remainingSeconds))")
                .onReceive(timer) { _ in
                    if isCounting && remainingSeconds > 0 {
                        remainingSeconds -= 1
                    }
                }
        }.padding()
        
        VStack {
            HStack {
                Button("+10 SEC") {
                    remainingSeconds += 10
                }.padding()
                Button("+20 SEC") {
                    remainingSeconds += 20
                }.padding()
            }.padding()
            
            HStack {
                Button("START") {
                    isCounting = true
                }.padding()
                Button("STOP") {
                    isCounting = false
                }.padding()
            }.padding()
        }
    }
    
    private func timeString(from totalSeconds: Int) -> String {
        let hours = totalSeconds / 3600
        let minutes = (totalSeconds % 3600) / 60
        let seconds = totalSeconds % 60
        return String(format:"%02i:%02i:%02i",hours,minutes, seconds)
    }
}

And obviously, you should format your dates by using Swift's DateFormatter

And here are some resources for you:

How to use a timer with SwiftUI

Working with dates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM