首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更新LazyVGrid列表

更新LazyVGrid列表
EN

Stack Overflow用户
提问于 2021-08-16 19:33:23
回答 1查看 127关注 0票数 0

我有一个LazyVGrid列表,它需要在数据更新时进行更新。数据位于单例类中。

代码语言:javascript
复制
class BluetoothManager: NSObject {
    static let shared = BluetoothManager()
    @objc dynamic private(set) var stations: [BHStation] = []
}

这个列表是

代码语言:javascript
复制
var body: some View {
    let columns: [GridItem] = Array(repeating: .init(.flexible()), count: UIDevice.current.userInterfaceIdiom == .pad ? 2 : 1)
    ScrollView {
        LazyVGrid(columns: columns, alignment: .center, spacing: 10, pinnedViews: [], content: {
            ForEach(BluetoothManager.shared.stations, id: \.peripheral.identifier) { item in
                NavigationLink(destination: DetailView()) {
                    MainCell()
                } 
            }
        })
    }
}

我尝试在@Published中使用ObservableObject,或者使用@State/@Binding,但都不起作用。

如何在更新stations时更新列表?在其他UIKit类中必须使用@objc dynamic

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-16 19:44:02

为了让SwiftUI View知道如何更新,您应该使用具有@Published属性的ObservableObject,并将其存储为@ObservedObject@StateObject

代码语言:javascript
复制
class BluetoothManager: NSObject, ObservableObject {
    static let shared = BluetoothManager()
    private override init() { }
    @Published var stations: [BHStation] = []
}
代码语言:javascript
复制
struct ContentView : View {
    @ObservedObject private var manager = BluetoothManager.shared
    
    var body: some View {
        let columns: [GridItem] = Array(repeating: .init(.flexible()), count: UIDevice.current.userInterfaceIdiom == .pad ? 2 : 1)
        ScrollView {
            LazyVGrid(columns: columns, alignment: .center, spacing: 10, pinnedViews: [], content: {
                ForEach(manager.stations, id: \.peripheral.identifier) { item in //<-- Here
                    NavigationLink(destination: DetailView()) {
                        MainCell()
                    }
                }
            })
        }
    }
}

@Published可能会干扰您的@objc要求,但是由于您没有给出任何关于如何在UIKit中使用它或为什么需要它的信息,所以不可能直接说出修复是什么。在UIKit中与其交互时,您可能需要使用不同的设置器。

此外,请注意,除非存储的模型类型(BHStation)是struct,否则@Published不会按预期进行更新。如果它是一个类,您可能需要直接调用objectWillChange以使@Published发布器正确触发。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68808320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档