Skip to content

Detecting changes to the SwiftUI Toggle

   

Detects changes to the SwiftUI toggle and executes a print statement.

SwiftUI Toggle Action

Reference: How can I trigger an action when a swiftUI toggle() is toggled?

import SwiftUI
class ContentViewViewModel: ObservableObject {
@Published var toggleValue: Bool = true {
didSet {
print("value did change")
}
}
}
struct ContentView: View {
@ObservedObject(initialValue: ContentViewViewModel()) var viewModel: ContentViewViewModel
var body: some View {
Toggle(isOn: $viewModel.toggleValue) {
HStack {
Text("value = " + String(viewModel.toggleValue))
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

  1. Creating a multi-line picker in SwiftUI
  2. Don't show the Label in the SwiftUI Picker
  3. Displaying a Picker in SwiftUI
  4. Calling the transition source method from the view of the screen transition destination in SwiftUI
  5. Create a sequential numbered array in Swift
  6. Using TabView to switch screens (SwiftUI)
  7. Transition from one ListView to another (SwiftUI)