Hey folks,
I'm trying to move a Picker and Button out of ContentView into a new struct called TimePicker. After moving the Button out of ContentView, the timeRemaining variable no longer updates in ContentView.
I'm confused why that is happening because I can see in the console that the function setTimerlength is still working, the timeRemaining var is still getting updated in the AppTimer class, but that change is not making it's way to the ContentView.
I can move the button back to ContentView to get this working, but I figure the reason this isn't working is because I'm misunderstanding something fundamental about SwiftUI and I should take the time to learn it.
Many thanks!
class AppTimer: ObservableObject {
// This is what I want to update in ContentView
@Published var timeRemaining: TimeInterval = 0
let timePickerOptions = [5, 10, 15, 20, 30, 45, 60]
// This takes the selected value from the Picker
// and updates timeRemaining
func setTimerLength(index: Int) {
let minutes = timePickerOptions[index]
let seconds = Double(minutes) * 60
timeRemaining = seconds
}
}
// This is what I pulled out of ContentView
struct TimePicker: View {
@ObservedObject var appTimer = AppTimer()
@Binding var timePickerIndex: Int
var body: some View {
Picker(selection: $timePickerIndex, label: Text("Meditation Duration")) {
ForEach(0 ..< appTimer.timePickerOptions.count) {
Text("\(appTimer.timePickerOptions[$0]) minutes")
}
}
// When this button is in ContentView, everything works as expected
Button("Done") {
appTimer.setTimerLength(index: timePickerIndex)
}
}
}
struct ContentView: View {
@ObservedObject var appTimer = AppTimer()
@State private var timePickerIndex = 0
var body: some View {
// This is what stopped updating when I moved the button
// out of ContentView
Text("Time Remaining: \(appTimer.timeRemaining)")
TimePicker(timePickerIndex: $timePickerIndex)
}
}