我有一个LazyVGrid列表,它需要在数据更新时进行更新。数据位于单例类中。
class BluetoothManager: NSObject {
static let shared = BluetoothManager()
@objc dynamic private(set) var stations: [BHStation] = []
}这个列表是
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。
发布于 2021-08-16 19:44:02
为了让SwiftUI View知道如何更新,您应该使用具有@Published属性的ObservableObject,并将其存储为@ObservedObject或@StateObject
class BluetoothManager: NSObject, ObservableObject {
static let shared = BluetoothManager()
private override init() { }
@Published var stations: [BHStation] = []
}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发布器正确触发。
https://stackoverflow.com/questions/68808320
复制相似问题