更好的方法是使用 @State 或 @ObservableObject

Better way use @State or @ObservableObject

大家好,我有一个关于@State vs @ObservableObjectSwiftUI

的问题

我有一个包含 LazyHGrid 的视图 要拥有 LazyHGrid 自定义单元格 ,我更愿意使用自定义单元格创建一个新的 struct


视图层次结构如下:

struct View1 -> struct LazyHGrid -> struct LazyHGridCustomCell

View1 中,我有一个文本,每次选择时都必须用 LazyHGridCustomCell 的内容替换。

在这一点上,鉴于我的层次结构,我应该使用 @State@Binding 来更新文本还是更好 @ObservableObject?

如果我想使用 @State 包装器,我会发现自己是这样的:

我想知道这是不是正确的方法或考虑 @ObservableObject

我根据我的问题创建了一个代码示例..创建它只是为了让您理解我的意思以避免被误解

我想知道创造这种情况或使用 @ObservableObject

是否正确

如果这条路径是错误的,你能告诉我一个获得正确结果的正确方法的例子吗?

感谢建议


struct View1: View {
    @State private var name: String
    
    var body: some View {
        Text(name)
        LazyHGridView(name: $name)
    }
}

struct LazyHGridView: View { 
    @Binding var name: String
    
    var body: some View {
        LazyHGrid(rows: Array(repeating: GridItem(), count: 2)) {
            ForEach(reservationTimeItems) { item in
                LazyHGridCustomCell(name: $name)
            }
        }
    }
}
    
struct LazyHGridCustomCell: View {
    @Binding var name: String
    
    var body: some View {
        Text(name)
            .foregroundColor(.white)
    }
}

根据 Data Essentials in SwiftUI (WWDC 2020) 在 9:46 的说法,您应该使用 State,因为 ObservableObject 用于模型数据。

State is designed for transient UI state that is local to a view. In this section, I want to move your attention to designing your model and explain all the tools that SwiftUI provides to you. Typically, in your app, you store and process data by using a data model that is separate from its UI. This is when you reach a critical point where you need to manage the life cycle of your data, including persisting and syncing it, handle side-effects, and, more generally, integrate it with existing components. This is when you should use ObservableObject. First, let's take a look at how ObservableObject is defined.