如何在swift用户界面中观察属性

fsi0uk1n  于 2023-01-19  发布在  Swift
关注(0)|答案(1)|浏览(136)

如何在SwiftUI中观察属性值。我知道一些基本的发布者和观察者模式。但是这里有一个我无法实现的场景。

class ScanedDevice: NSObject, Identifiable {

//some variables
var CurrentStatusText: String = "Pending"

}

这里,CurrentStatusText由其他一些更新状态的回调方法更改。
这里有我正在使用的ViewModel类

class SampleViewModel: ObservableObject{
    @Published  var devicesToUpdated : [ScanedDevice] = []
}

雨燕成分:

struct ReviewView: View {
    @ObservedObject var viewmodel:SampleViewModel
 var body: some View {
   
      ForEach(viewmode.devicesToUpdated){ device in

      Text(device.CurrentStatusText)
}
}
    }

在UI中,我想查看实时状态
我尝试在ScanDevice类中使用Publisher,但肯定可以在2层中使用它

agxfikkp

agxfikkp1#

您可以观察您的class ScanedDevice,但是您需要手动使用objectWillChange.send()来操作可观察到的更改,如本示例代码所示。

class ScanedDevice: NSObject, Identifiable {
    var name: String = "some name"
    var currentStatusText: String = "Pending"
    
    init(name: String) {
        self.name = name
    }
}

class SampleViewModel: ObservableObject{
    @Published  var devicesToUpdated: [ScanedDevice] = []
}

struct ReviewView: View {
    @ObservedObject var viewmodel: SampleViewModel
    
    var body: some View {
        VStack (spacing: 33) {
            ForEach(viewmodel.devicesToUpdated){ device in
                HStack {
                    Text(device.name)
                    Text(device.currentStatusText).foregroundColor(.red)
                }
                Button("Change \(device.name)") {
                    viewmodel.objectWillChange.send()  // <--- here
                    device.currentStatusText = UUID().uuidString
                }.buttonStyle(.bordered)
            }
        }
        
    }
}

struct ContentView: View {
    @StateObject var viewmodel = SampleViewModel()
    
    var body: some View {
        ReviewView(viewmodel: viewmodel)
            .onAppear {
               viewmodel.devicesToUpdated = [ScanedDevice(name: "device-1"), ScanedDevice(name: "device-2")]
            }
    }
}

相关问题