【发布时间】:2021-03-16 21:24:15
【问题描述】:
我有一个名为 AppData 的 CustomType,它看起来像这样:
struct AppData {
var stringOfText: String
var colorOfText: Color
}
我在我的视图中使用这个 AppData 作为状态或绑定,我的项目中有 2 个视图,名为:ContentView 和另一个称为 BindingView。在我的 BindingView 中,我只是使用 AppData 的颜色信息。我期待我的 BindingView 呈现或响应颜色信息的变化!实际上 BindingView 会为stringOfText 呈现自己,这是完全没有必要的,因为视图中不使用该数据。我认为可能 BindingView 不仅考虑 colorOfText 还考虑所有携带此数据的包,即 appData 所以我决定帮助 BindingView 了解它应该何时呈现本身,我制作了那个 View Equatable,但这甚至没有帮助。仍然 BindingView 刷新并在 stringOfText 的更改上呈现自己,这是浪费渲染。在使用 CustomType 作为我的 State 或 Binding 的类型时,如何解决这个不必要的渲染问题。
struct ContentView: View {
@State private var appData: AppData = AppData(stringOfText: "Hello, world!", colorOfText: Color.purple)
var body: some View {
print("rendering ContentView")
return VStack(spacing: 20) {
Spacer()
EquatableView(content: BindingView(appData: $appData))
//BindingView(appData: $appData).equatable()
Spacer()
Button("update stringOfText from ContentView") { appData.stringOfText += " updated"}
Button("update colorOfText from ContentView") { appData.colorOfText = Color.red }
Spacer()
}
}
}
struct BindingView: View, Equatable {
@Binding var appData: AppData
var body: some View {
print("rendering BindingView")
return Text("123")
.bold()
.foregroundColor(appData.colorOfText)
}
static func == (lhs: BindingView, rhs: BindingView) -> Bool {
print("Equatable function used!")
return lhs.appData.colorOfText == rhs.appData.colorOfText
}
}
【问题讨论】: