切换注释的地方,就知道效果了
import SwiftUI
class Counter: ObservableObject {
@Published var count : Int = 0
}
struct CounterView: View {
// @ObservedObject var counter = Counter()
@StateObject var counter = Counter()
var body: some View {
VStack {
Text("CounterView count number")
Text("\(counter.count)")
Button("Increment CounterView count") {
counter.count += 1
}
}.padding()
.background(Color.red)
}
}
struct ContentView: View {
@State private var value = 0
var body: some View {
VStack {
Text("ContentView value number")
Text("\(value)")
Button("Increment ContentView value") {
value += 1
}
CounterView()
}.padding()
.background(Color.green)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
配合文章以及视频 效果更佳