Detects changes to the SwiftUI toggle and executes a print statement.
Reference: How can I trigger an action when a swiftUI toggle() is toggled?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} |