【问题标题】:How to fire a function on @State variable change from Apple Watch Digital Crown with SwiftUI?如何使用 SwiftUI 从 Apple Watch Digital Crown 触发 @State 变量更改的函数?
【发布时间】:2023-03-18 12:33:02
【问题描述】:

下面的代码在 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() {

        }

    }
}

【问题讨论】:

    标签: swift binding state watchkit swiftui


    【解决方案1】:

    其实,如果你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.
    }
    

    【讨论】:

    • 如果您使用 .onChange(of:perform:) 而不是 .onReceive(_:perform),则无需使用 Combine。如果需要,您甚至可以在闭包中捕获旧值。
    【解决方案2】:

    不幸的是,现在最简单的做法是使用自定义绑定来包装您的crownValue。 (我说很遗憾,因为我与 Apple 有一张公开票,关于 @State 缺少 didSet 以及如何解决它,目前还没有解决方案。)

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

    并使用它:

     SomeView()
       .digitalCrownRotation(self.crownValueBinding, ...) // NOTE: No $ sign!
    

    【讨论】:

    • 回到另一个项目中的相同问题,您介意解释一下为什么在解决方案中省略 $ 符号吗?我知道这是必要的,但不太明白为什么。
    • @State var crownValue ... 是一个包装好的 @State 属性。当您使用self.$crownValue 时,它会访问@State 的“预计值”,即Binding。但是,crownValueBinding已经是我们在该代码中明确创建的Binding。查看the documentation 了解更多信息。在该页面上搜索“property wrapper”和“projected value”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2019-11-10
    • 2020-04-10
    相关资源
    最近更新 更多