I would like to stop and start the timer by a boolean value, but thats not working. isEditMode variable binded to an other view's button. I would be very grateful if someone could help me.
There is the code:
import SwiftUI
import Combine
public struct ClockView: View {
var width = UIScreen.main.bounds.width
@State var currentTime = Time(sec: 0, min: 0, hour: 0.0)
@State var timer = Timer.publish(every: 1, on: .current, in: .default).autoconnect()
@State var connectedTimer: Cancellable? = nil
@Binding var isEditMode: Bool
public var body: some View {
ZStack {
//sec
Rectangle()
.fill(Color.red)
.opacity(isEditMode ? 0 : 1)
.frame(width: 1, height: (width - 175) / 2)
.offset(y: -(width - 155) / 4)
.rotationEffect(.degrees(Double(currentTime.sec * 6)))
//min
Rectangle()
.fill(Color.secondary)
.opacity(0.9)
.frame(width: 2, height: (width - 200) / 2)
.offset(y: -(width - 180) / 4)
.rotationEffect(.degrees(Double(currentTime.min * 6)))
//hour
Rectangle()
.fill(Color.primary)
.frame(width: 3, height: (width - 220) / 2)
.offset(y: -(width - 202) / 4)
.rotationEffect(.degrees(Double(currentTime.hour * 30)))
}.frame(width: width - 80, height: width - 80)
//first call
.onAppear(perform: {
withAnimation(Animation.linear(duration: 0.01)) {
self.currentTime = getCurrentTime()
}
})
//time changes
.onReceive(timer) { i in
withAnimation(Animation.linear(duration: 0.01)) {
if self.isEditMode {
self.timer.upstream.connect().cancel()
}
else if !self.isEditMode {
self.timer = Timer.publish(every: 1, on: .current, in: .default).autoconnect()
}
self.currentTime = getCurrentTime()
}
}
}
}
func getCurrentTime() -> Time {
let calendar = Calendar.current
let sec = calendar.component(.second, from: Date())
let min = calendar.component(.minute, from: Date())
let hour: Double = Double(calendar.component(.hour, from: Date())) + Double(min) / 60
return Time(sec: sec, min: min, hour: hour)
}
struct Time {
var sec: Int
var min: Int
var hour: Double
}
struct ClockView_Previews: PreviewProvider {
static var previews: some View {
ClockView(isEditMode: .constant(false))
}
}```