可以在Background view修饰符上使用id来唯一标识其视图,这样即使父视图重新加载,该视图也不会被重新创建。
代码示例:
struct ContentView: View { @State private var counter = 0
var body: some View {
VStack {
BackgroundView(id: "background") {
Color.green.frame(width: 200, height: 100)
}
Button("Increment") {
counter += 1
}
}
}
}
struct BackgroundView
init(id: String, @ViewBuilder content: () -> Content) {
self.id = id
self.content = content()
}
var body: some View {
content.background(id: id)
}
}
在这个例子中,我们使用了BackgroundView修饰符来创建一个绿色的框,然后在它上面添加了一个Button。当Button被点击时,计数器将会增加,但是BackgroundView中的视图不会被重新创建,因为我们使用了id来标识它。