๐ธobservable object
SwiftUI โฉ view โฉ state โฉ observable object
An observable object is an object of any class type that conforms to the ObservableObject protocol, any changes to its published values will cause all views using those values to automatically update, reflecting the changes.
An observable object is a custom object (reference type) for your data that can be bound to a view from storage in SwiftUIโs environment.
Use ObservableObject to declare an observable object type.
Use @Published to declare published values in an observable object type.
Use @StateObject to initialize an observable object.
data model๏ผdata shared with any views in your app.
environment object๏ผan observable object, which is put in the environment by calling an ancester view's .environmentObject(_:) modifier.
ๅ้ก
ๅจ่ท CS193P ๅฐ็ฌฌไธ่ชฒ็ๆๅ๏ผๅฆๆๆ็ ง่ชฒ็จไธ็็จๅผ็ขผๅๅฐไธๅ็็ งๆ๏ผ็จๅผๅฏไปฅๆญฃๅธธๅท่กใ
ไฝๅฆๆๆ
่ชๅฐ Card ้ๅ struct ๆนๆไธๅ
้ตๅพช Identifiable ๅๆไน้ตๅพช Equatable๏ผ้ๆๅฐฑๅบ็พๅ้กไบ๏ผใๅจๆๅก็็ๆๅ๏ผๅก็ไธๆ็ฟป้ขใ๏ผ้ๅ้กไผผไน่ท ForEach(data){ ... } ่ชๆณ่ฃก้ข๏ผdata
้จๅ็ .id ๆ้ไฟใ
ๅฐฑ็ฎ @Published var viewModel ๆดๆฐไบ๏ผไฝๅจ ForEach(viewModel.cards) ่ฃก้ข็ cards ็ id ไธฆๆฒๆ่ฎๆด๏ผๅๅ ไธ Card ๆฌ่บซ้ตๅพช Equatable (้้ปๅพ้่ฆ๏ผๅ ็บๅฆๆๆฒๆ Equatable๏ผ็จๅผๅฏๆญฃๅธธๅท่ก)๏ผ้ ๆ SwiftUI ๅคๆท EmojiMemoryGameView ็ body ่ฃก้ข็ ForEach ้จๅไธ้ๆดๆฐ๏ผๅ ๆญคๅฐฑไธๆ็ฟป้ขไบใ
ๆ Equatable ่ทๆฒๆ Equatable ๆ้บผๅทฎ้ฃ้บผๅคๅข๏ผSwiftUI ๆฏๅฆไฝๅคๆทไธๅ view ๅฐๅบ่ฆไธ่ฆๆดๆฐๅข๏ผ
ๅ่่ณๆ
SwiftUI โฉ View Layout & Presentation โฉ ForEach
Swift โฉ Standard Library โฉ Basic Behaviors โฉ Identifiable
Last updated