簡體   English   中英

為什么這個 swiftui 視圖沒有更新?

[英]Why does this swiftui view not update?

考慮以下代碼塊:import SwiftUI

struct MeasurementReading: View, Equatable {

    @ObservedObject var ble: BluetoothConnectionmanager
    @GestureState var isDetectTap = false
    @State var MyText:String = "Wait"

    static func == (lhs: MeasurementReading, rhs: MeasurementReading)->Bool{
        return lhs.MyText == rhs.MyText
    }

    var body: some View {
        let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

        return HStack {
            Spacer()
            VStack{
                Button(action:{
                    self.MyText = "\(self.ble.getValue()!) mV"
                    print("Text is \(self.MyText as NSString)")
                }, label: {
                    Text(MyText)
                        .font(.system(size: 40))
                        .bold()
                        .foregroundColor(Color.black)
                        .padding(.trailing, 15)
                        .frame(height: 100)
                })
                Button(action: {
                    self.MyText = "\(self.ble.getValue()!) mV"
                    print("Text is \(self.MyText as NSString)")

                }, label: {
                    Text(MyText)
                        .font(.system(size: 25))
                        .padding(.top, -20)
                        .padding(.bottom, 20)
                        .foregroundColor(Color.black)
                })
            }
        }.onReceive(timer)
        { _ in // TIMER FUNCTIONALITY HERE
            self.MyText = "\(self.ble.getValue()!) mV"
            print("Text is \(self.MyText)")
        }
    }
}


struct MeasurementReading_Previews: PreviewProvider {
    static var previews: some View {
        MeasurementReading(ble: BluetoothConnectionmanager())
    }
}

每隔 1 秒,將從 BLE 系統讀取的正確值分配給 MyText,然后 MyText 將使用更新的值正確打印到調試輸出。

這里的問題是視圖 MeasurementReading 不會更新。 此外,在任何項目上使用閉包也具有相同的行為(變量被更新,它被正確輸出但沒有視圖更新)例如 .onTap{....} 將具有相同的行為或任何其他 .onXXXX 閉包。 我可以使用 MyText 狀態的新值更新視圖的唯一方法是將行為放在一個按鈕中。

我的問題是:為什么即使狀態變量通過 Timer 或 .onXXXX 閉包更改,視圖也不會更新?

您需要將ble值設置為更新的計時器值:

如果沒有正確測試。 我還認為您的BluetoothConnectionmanager需要是一個@State屬性才能工作。

@State var ble: BluetoothConnectionmanager

.onReceive(timer) { value in // value is the updated value
    self.ble.value = value
    self.MyText = "\(self.ble.getValue()!) mV"
    print("Text is \(self.MyText)")
}

查看示例以了解計時器如何與Date()對象一起使用。

暫無
暫無

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

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