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

时间:2019-11-17 22:05:14

标签: swift binding state watchkit swiftui

下面的代码在SwiftUI中创建一个环,该环在旋转Digital Crown时完成。我想在“ crownValue”状态变量的值达到5.0(即圆圈完全可见)时触发一个函数。

我该如何具有对表冠值变化做出反应以便执行Web请求的功能?

谢谢

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() {

        }

    }
}

2 个答案:

答案 0 :(得分:0)

不幸的是,目前最容易做的事情是使用包装crownValue的自定义绑定。 (我很遗憾地说,因为我与苹果公司就缺少didSet的{​​{1}}问题以及如何解决问题(尚未解决)进行了公开讨论。)

@State

并使用它:


var crownValueBinding: Binding<Double> {
  Binding<Double>(
    get: { self.crownValue },
    set: { newValue in
      self.crownValue = newValue
      self.myFunc() // Whatever you like
    }
  )
}

答案 1 :(得分:0)

实际上,如果您import combine

您可以执行以下操作:

 .....

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

    }.onReceive(Just(crownValue)) { output in
        print(output) // Here is the answer.
    }