簡體   English   中英

如何觀察swift ui中的屬性

[英]How to observer a property in swift ui

如何觀察 SwiftUI 中的屬性值。我知道一些基本的發布者和觀察者模式。 但這是我無法實現的場景。

class ScanedDevice: NSObject, Identifiable {

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

}

這里 CurrentStatusText 被更新狀態的一些其他回調方法更改。

這里有 Model class 我正在使用

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

swiftui 組件:

struct ReviewView: View {
    @ObservedObject var model: SampleModel
    var body: some View {
        ForEach(model.devicesToUpdated){ device in
            Text(device.currentStatusText)
        }
    }
}

在 UI 中,我想查看實時狀態

我嘗試在 ScanDevice class 中使用發布者,但肯定可以在 2 層中使用它

您可以觀察您的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")]
            }
    }
}

暫無
暫無

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

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