如何使用SwiftUI从Apple Watch Digital Crown触发@State变量更改的函数?

Zai*_*med 3 binding state swift watchkit swiftui

下面的代码在 SwiftUI 中创建一个环,当数字表冠旋转时完成。我想在“crownValue”状态变量达到 5.0 的值时触发一个函数,也就是当圆圈完全可见时。

我怎样才能有一个对冠值变化做出反应的函数来执行网络请求?

谢谢

struct commandDetailView: View {

    @State var crownValue = 0.1


    var body: some View {
        VStack {
            Circle()
                .trim(from: 0.0, to: CGFloat(crownValue / 5.0))
                .stroke(Color.blue, style: StrokeStyle(lineWidth: 12, lineCap: CGLineCap.round, lineJoin: .round))
                .frame(width: 120, height: 120)

            Text("Spin to Start Car")


        }
    .focusable(true)
        .digitalCrownRotation($crownValue, from: 0.1, through: 5.0, sensitivity: .low, isContinuous: false, isHapticFeedbackEnabled: true)
        .onAppear() {

        }

    }
}
Run Code Online (Sandbox Code Playgroud)

E.C*_*oms 7

实际上,如果您import Combine,您可以执行以下操作:

[...]
.focusable(true)
.digitalCrownRotation($crownValue, from: 0.1, through: 5.0, sensitivity: .low, isContinuous: false, isHapticFeedbackEnabled: true)
.onReceive(Just(crownValue)) { output in
    print(output) // Here is the answer.
}
Run Code Online (Sandbox Code Playgroud)