@StateObjectを利用することで親ビューの再描画でオブジェクトが初期化されなくなる
ContentView.swift
struct ContentView: View { @State var isShow = true var body: some View { VStack (alignment: .leading, spacing: 20){ ValueView1() ValueView2() Toggle(isOn: $isShow){ }.frame(width: 50).padding(.top, 30) if isShow { Text("Hello, World!").font(.largeTitle) } Spacer() } .padding() } } struct ValueView2: View { @StateObject var maker = ValueMaker() var body: some View { VStack (alignment: .leading, spacing: 10){ Text("\(maker.value)") .font(.title) .foregroundColor((maker.value > 0.8) ? .white : .gray) .background((maker.value > 0.8) ? Color.red : Color.white) HStack { Text("カウンタ:") Text("\(maker.counter)").font(.largeTitle) } } .background(Color.blue.opacity(0.3)) .frame(width: 200, height: 80) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() ValueView1() ValueView2() } }
ValueMarker.swift
class ValueMaker: ObservableObject { @Published var value: Double @Published var counter: Int = 0 private var timer: Timer init() { value = 0.0 timer = Timer() start() } func start(){ timer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in self.value = Double.random(in: 0 ... 1) if self.value > 0.8 { self.counter += 1 } } } } struct ValueView1: View { @ObservedObject var maker = ValueMaker() var body: some View { VStack (alignment: .leading, spacing: 10){ Text("\(maker.value)") .font(.title) .foregroundColor((maker.value > 0.8) ? .white : .gray) .background((maker.value > 0.8) ? Color.red : Color.white) HStack { Text("カウンタ:") Text("\(maker.counter)").font(.largeTitle) } } .background(Color.yellow.opacity(0.3)) .frame(width: 200, height: 80) } }
なんかうまくいかんなー