简体   繁体   English

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

[英]How to use @EnvironmentObject to populate and update list automatically in SwiftUI?

Like the title says, I'm trying to use an @EnvironmentObject that holds data to populate and update a List automatically in SwiftUI.就像标题所说的那样,我正在尝试使用保存数据的 @EnvironmentObject 在 SwiftUI 中自动填充和更新列表。

For context, I'm building an app that is supposed to show a list of locations.对于上下文,我正在构建一个应该显示位置列表的应用程序。 The location data will be shown in multiple places of my app and will be changing during use, so I thought an @EnvironmentObject would be perfect for holding the data.位置数据将显示在我的应用程序的多个位置,并且在使用过程中会发生变化,所以我认为 @EnvironmentObject 非常适合保存数据。 But, I'm having trouble feeding an @EnvironmentObject to populate a List() and having the list update as the @EnvironmentObject changes.但是,我无法提供 @EnvironmentObject 来填充 List() 并在 @EnvironmentObject 更改时更新列表。


Below is the struct I created for the location data I want to display:下面是我为要显示的位置数据创建的结构:

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

Below is my SceneDelegate.swift file, where I create the @EnvironmentObject and the class it references:下面是我的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.
    }


}

And, here is the my ContentView.swift file where I want to use the @EnvironmentObject above to populate and update a List() automatically:而且,这是我的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()
        }
    }
}

Can anyone show me how to alter my code so that I can display and update data in a list using an @EnvironmentObject??谁能告诉我如何更改我的代码,以便我可以使用@EnvironmentObject 在列表中显示和更新数据?

Or is there a better way to implement a dynamic List?或者有没有更好的方法来实现动态列表?

Have a look at the following tutorials:看看以下教程:

How to use environmentobject to share data 如何使用环境对象来共享数据

Apple - handling user inputs Apple - 处理用户输入

First You need a @Published property wrapper for your code to work.首先,您需要一个 @Published 属性包装器才能使您的代码工作。

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

Than adjust yout Scene delegate比调整你的场景委托

var window: UIWindow?
var vDArray = VenDataArray()

let contentView = ContentView().environmentObject(vDArray)

Note: I have adjusted the variables with lowerCamelCase acc.注意:我已经用lowerCamelCase acc 调整了变量。 to the API design guidelines API 设计指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM