UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Pausing countdown with button

Forums > SwiftUI

I want to add a simple countdown like this. How could I pause this timer with another button?

struct ContentView: View {
    @State var timeRemaining = 10
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        Text("\(timeRemaining)")
            .onReceive(timer) { _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                }
            }
    }
}

2      

See here: https://www.hackingwithswift.com/books/ios-swiftui/triggering-events-repeatedly-using-a-timer

var body: some View {
        VStack {
        Text("\(timeRemaining)")
            .onReceive(timer) { _ in
                if self.timeRemaining > 0 {
                    self.timeRemaining -= 1
                }
            }
            Button("Stop", action: {
                self.timer.upstream.connect().cancel()
            })
        }
    }

2      

You could look at HWS+ Creating completely custom buttons using PrimitiveButtonStyle give you a button that when pressed again cancel action

make this struct

import Combine
import SwiftUI

struct CancellableButtonStyle: PrimitiveButtonStyle {
    private struct CancellableButton: View {
        @State private var timerSubscription: Cancellable?
        @State private var timer = Timer.publish(every: 1, on: .main, in: .common)
        @State private var countDown = 0

        let configuration: Configuration
        let timeOut: Int

        var body: some View {
            Button(action: {
                if self.timerSubscription == nil {
                    self.timer = Timer.publish(every: 1, on: .main, in: .common)
                    self.timerSubscription = self.timer.connect()
                    self.countDown = self.timeOut
                } else {
                    self.cancelTimer()
                }
            }) {
                if timerSubscription == nil {
                    configuration.label

                } else {
                    Text("Cancel? \(countDown)")
                }
            }
            .buttonStyle(ExampleButtonStyle(backgroundColor: timerSubscription == nil ? .blue : .red))
            .onReceive(timer) { _ in
                if self.countDown > 1 {
                    self.countDown -= 1
                } else {
                    self.configuration.trigger()
                    self.cancelTimer()
                }
            }
        }

        func cancelTimer() {
            timerSubscription?.cancel()
            timerSubscription = nil
        }
    }

    var timeOut = 3 // set this number of second before action will take place

    func makeBody(configuration: Configuration) -> some View {
        CancellableButton(configuration: configuration, timeOut: timeOut)
    }
}

then you can add this to your Button

Button(action: {
    print("Pressed")
}) {
    Text("Cancellable")
}
.buttonStyle(CancellableButtonStyle())
.padding()

2      

Thanks that works now :) @Hatsushira

Is there also a way to make it a pause button? So that I can create a seperate button to continue the timer

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.