The background color of SecondView
doesn’t change as expected when I push the button, however, the random number in ThirdView
updates each time. Why does this happen, both secondView and thirdView have no explicit dependency on the state, I think both of them should not be re-created.
Apple Docs: When the @State value changes, SwiftUI updates the parts of the view hierarchy that depend on the value.
struct ParentView: View {
@State var counter: Int = 0
var body: some View {
VStack {
Text("ContentView (counter)")
SecondView()
ThirdView()
Button {
counter += 1
} label: {
Text("Go!")
}
}
}
}
struct SecondView: View {
var body: some View {
Text("SecondView")
.background(.debug)
}
}
struct ThirdView: View {
let randomNumber = Int.random(in: 1...100)
var body: some View {
Text("Random Number: (randomNumber)")
}
}
public extension ShapeStyle where Self == Color {
static var debug: Color {
Color(
red: .random(in: 0...1),
green: .random(in: 0...1),
blue: .random(in: 0...1)
)
}
}