簡體   English   中英

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

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

就像標題所說的那樣,我正在嘗試使用保存數據的 @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 在列表中顯示和更新數據?

或者有沒有更好的方法來實現動態列表?

看看以下教程:

如何使用環境對象來共享數據

Apple - 處理用戶輸入

首先,您需要一個 @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 設計指南

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM