如何使用@EnvironmentObject 在 SwiftUI 中自动填充和更新列表?

Posted

技术标签:

【中文标题】如何使用@EnvironmentObject 在 SwiftUI 中自动填充和更新列表?【英文标题】:How to use @EnvironmentObject to populate and update list automatically in SwiftUI? 【发布时间】:2019-12-31 21:45:18 【问题描述】:

正如标题所说,我正在尝试使用一个 @EnvironmentObject 来保存数据,以便在 SwiftUI 中自动填充和更新列表。

对于上下文,我正在构建一个应该显示位置列表的应用程序。位置数据将显示在我的应用程序的多个位置,并且在使用过程中会发生变化,所以我认为@EnvironmentObject 非常适合保存数据。但是,我无法提供 @EnvironmentObject 来填充 List() 并随着 @EnvironmentObject 的变化而更新列表。


下面是我为要显示的位置数据创建的结构:

struct ListVenue : Identifiable 
    var id = UUID()
    var name: String
    var formatted_address : String?
    var website : String?    

下面是我的 SceneDelegate.swift 文件,我在其中创建 @EnvironmentObject 及其引用的类:

import UIKit
import SwiftUI


class venDataArray: ObservableObject 
    var array : [ListVenue] = [ListVenue(name: "test_name")]



class SceneDelegate: UIResponder, UIWindowSceneDelegate 

    var window: UIWindow?
    @EnvironmentObject var VDArray: venDataArray

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) 
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // Create the SwiftUI view that provides the window contents.
        let contentView = ContentView().environmentObject(VDArray)

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene 
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        
    

    func sceneDidDisconnect(_ scene: UIScene) 
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    

    func sceneDidBecomeActive(_ scene: UIScene) 
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    

    func sceneWillResignActive(_ scene: UIScene) 
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    

    func sceneWillEnterForeground(_ scene: UIScene) 
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    

    func sceneDidEnterBackground(_ scene: UIScene) 
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    



而且,这是我的 ContentView.swift 文件,我想在其中使用上面的 @EnvironmentObject 自动填充和更新 List():

import SwiftUI



struct ContentView: View 


    @EnvironmentObject var VDArray: venDataArray


    var body: some View 

    VStack(alignment: .leading) 

        Text("Location List")

    //  This is where im failing at having a list take in an @EnvironmentObject
        List(VDArray)  ListVenue in 
        //  vvv  This is the view I want displayed for each item in the @EnvironmentObject  vvv
            VenueRowTest()
        
    


谁能告诉我如何更改我的代码,以便我可以使用@EnvironmentObject 显示和更新列表中的数据?

或者有没有更好的方法来实现动态列表?

【问题讨论】:

【参考方案1】:

看看以下教程:

How to use environmentobject to share data

Apple - handling user inputs

首先,您需要一个 @Published 属性包装器才能使您的代码正常工作。

class VenDataArray: ObservableObject 
@Published var array : [ListVenue] = [ListVenue(name: "test_name")]

比调整你的场景委托

var window: UIWindow?
var vDArray = VenDataArray()

let contentView = ContentView().environmentObject(vDArray)

注意:我已经用 lowerCamelCase acc 调整了变量。 API 设计指南

【讨论】:

以上是关于如何使用@EnvironmentObject 在 SwiftUI 中自动填充和更新列表?的主要内容,如果未能解决你的问题,请参考以下文章

SwiftUI之如何使用@EnvironmentObject在视图之间共享数据

SwiftUI - 如何在@ObservableObject 中获取@EnvironmentObject 数据

SwiftUI中如何使用@EnvironmentObject在AppDelegate和SceneDelegate/Views之间共享数据

如何在现有的基于 Storyboard 的项目中设置 @EnvironmentObject?

SwiftUI - 如何使用 ObservedObject 或 EnvironmentObject 存储 GeometryReader 数据?

SwiftUI:可以访问祖先自定义`@EnvironmentObject`?如果是,如何?