There is DiscoView which is just a hardcoded text that should blink with the given period.
There is a parent view which may change that period. When period changes, I need to update the timer somehow.
let colors: [Color] = [.red, .green, .black, .yellow, .pink, .blue]
struct DiscoView: View {
var period: TimeInterval
@State var color: Int = 0
@State var timer: Timer? = nil
var body: some View {
Text("DISCO")
.foregroundColor(colors[color])
.onAppear {
self.timer = Timer.scheduledTimer(withTimeInterval: self.period, repeats: true) { _ in
self.color = (self.color + 1) % colors.count
}
}
.onDisappear {
self.timer?.invalidate()
}
}
}
struct DiscoManager: View {
@State var period: TimeInterval = 1
var body: some View {
VStack {
DiscoView(period: self.period)
HStack {
Button("Slower") {
self.period *= 2
}
Button("Faster") {
self.period /= 2
}
}
}
}
}
I think you need a @Binding... however, my solution doesn't really seem to solve your problem as when I watch the colors, the blinking rate doesn't look different even though the period variable is definitely changing...
let colors: [Color] = [.red, .green, .black, .yellow, .pink, .blue]
struct DiscoView: View {
@Binding var period: TimeInterval
@State var color: Int = 0
@State var timer: Timer? = nil
var body: some View {
Text("DISCO - period: \(String(period))")
.foregroundColor(colors[color])
.onAppear {
self.timer = Timer.scheduledTimer(withTimeInterval: self.period, repeats: true) { _ in
self.color = (self.color + 1) % colors.count
}
}
.onDisappear {
self.timer?.invalidate()
}
}
}
struct DiscoManager: View {
@State var period: TimeInterval = 1
var body: some View {
VStack {
DiscoView(period: self.$period)
HStack {
Button("Slower") {
self.period *= 2
}
Button("Faster") {
self.period /= 2
}
}
}
}
}