Advertisement
Milotronik

StateVsObserved

Feb 15th, 2025
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.96 KB | None | 0 0
  1. import SwiftUI
  2.  
  3. final class MyViewModel: ObservableObject {
  4.     @Published var counter: Int = 0
  5. }
  6.  
  7. struct MainView: View {
  8.     @StateObject var myViewModel = MyViewModel()
  9.     var body: some View {
  10.         VStack {
  11.             VStack(spacing: 0) {
  12.                 Group {
  13.                     Text("\(myViewModel.counter)")
  14.                         .font(.largeTitle)
  15.                 }
  16.                 .padding()
  17.                 .background { Color.white }
  18.                
  19.                 Button {
  20.                     myViewModel.counter += 1
  21.                 } label: {
  22.                     Text("Increment counter")
  23.                         .padding()
  24.                         .background { Color.white }
  25.                         .clipShape(Capsule())
  26.                 }
  27.                 .padding(8)
  28.                
  29.             }
  30.             .frame(maxWidth: .infinity, maxHeight: .infinity)
  31.             ChildView()
  32.  
  33.         }
  34.        
  35.     }
  36. }
  37.  
  38. struct ChildView: View {
  39.     // Changing it to @StateObject will keep the object value
  40.     @ObservedObject var viewModel: MyViewModel = MyViewModel()
  41.     var body: some View {
  42.         VStack {
  43.             Text("I'm the child: \(viewModel.counter)")
  44.                 .padding(50)
  45.                 .font(.largeTitle)
  46.                 .background {
  47.                     Color.random()
  48.                 }
  49.             Button {
  50.                 viewModel.counter += 1
  51.             } label: {
  52.                 Text("Increment counter in child")
  53.                     .padding()
  54.                     .foregroundStyle(.white)
  55.                     .background { Color.red }
  56.                     .clipShape(Capsule())
  57.             }
  58.         }
  59.     }
  60. }
  61.  
  62. #Preview {
  63.     MainView()
  64. }
  65.  
  66. extension Color {
  67.     static func random() -> Color {
  68.         return Color(
  69.             red: Double.random(in: 0...1),
  70.             green: Double.random(in: 0...1),
  71.             blue: Double.random(in: 0...1)
  72.         ).opacity(0.5)
  73.     }
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement