Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import SwiftUI
- final class MyViewModel: ObservableObject {
- @Published var counter: Int = 0
- }
- struct MainView: View {
- @StateObject var myViewModel = MyViewModel()
- var body: some View {
- VStack {
- VStack(spacing: 0) {
- Group {
- Text("\(myViewModel.counter)")
- .font(.largeTitle)
- }
- .padding()
- .background { Color.white }
- Button {
- myViewModel.counter += 1
- } label: {
- Text("Increment counter")
- .padding()
- .background { Color.white }
- .clipShape(Capsule())
- }
- .padding(8)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- ChildView()
- }
- }
- }
- struct ChildView: View {
- // Changing it to @StateObject will keep the object value
- @ObservedObject var viewModel: MyViewModel = MyViewModel()
- var body: some View {
- VStack {
- Text("I'm the child: \(viewModel.counter)")
- .padding(50)
- .font(.largeTitle)
- .background {
- Color.random()
- }
- Button {
- viewModel.counter += 1
- } label: {
- Text("Increment counter in child")
- .padding()
- .foregroundStyle(.white)
- .background { Color.red }
- .clipShape(Capsule())
- }
- }
- }
- }
- #Preview {
- MainView()
- }
- extension Color {
- static func random() -> Color {
- return Color(
- red: Double.random(in: 0...1),
- green: Double.random(in: 0...1),
- blue: Double.random(in: 0...1)
- ).opacity(0.5)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement