为什么这个swiftui视图不更新?

时间:2019-12-01 09:06:39

标签: ios swift xcode swiftui

请考虑以下代码块:     导入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状态的新值完全更新视图的唯一方法是将行为放在Button中。

我的问题是:为什么即使通过Timer或.onXXXX闭包更改状态变量,视图也不会更新?

1 个答案:

答案 0 :(得分:0)

您需要将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)")
}

看看this示例,了解计时器如何与Date()对象一起工作。