You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DigitalCrownRotation可变步长值实现失败,求问题排查

问题分析与解决方案

你遇到的问题核心在于:digitalCrownRotation 的 by 参数不会自动响应 counterValue 的状态变化。你的条件表达式 self.counterValue < 10.0 ? 1 : 20 只会在视图首次初始化时计算一次,之后无论 counterValue 怎么变化,步长都不会再更新了——这就是可变步长没生效的原因。

解决思路

我们需要手动监听 counterValue 的变化,动态更新步长值,再把这个动态更新的步长传给 digitalCrownRotation。具体步骤如下:

  • 添加一个 @State 变量存储当前的动态步长
  • 使用 .onChange 监听 counterValue 的变化,实时同步步长变量
  • 将动态步长变量传入 digitalCrownRotation 的 by 参数

修改后的完整代码

struct AdjustTimeView: View {
    @State private var counterValue: Double = 1.0
    // 新增:存储动态步长的状态变量
    @State private var currentStep: Double = 1.0
    
    var body: some View {
        VStack {
            ZStack {
                Clockface()
                VStack {
                    Text("\(Int(counterValue))")
                        .font(.headline)
                        .fontWeight(.medium)
                        .foregroundColor(Color("MyBlueColor"))
                        .multilineTextAlignment(.center)
                        .focusable(true)
                        // 改用动态更新的currentStep作为步长
                        .digitalCrownRotation($counterValue, 
                                             from: 1.0, 
                                             through: 180.0, 
                                             by: currentStep, 
                                             sensitivity: .medium, 
                                             isContinuous: false, 
                                             isHapticFeedbackEnabled: true)
                    Text("min")
                        .font(.footnote)
                }
            }
        }
        // 监听counterValue变化,实时调整步长
        .onChange(of: counterValue) { newValue in
            currentStep = newValue < 10.0 ? 1 : 20
        }
        .navigationBarTitle("Adjust time")
    }
}

额外说明

  • 如果你希望在 counterValue 等于10时仍保持步长1,可以把判断条件改为 newValue <= 10.0 ? 1 : 20,根据实际需求调整即可。
  • .onChange 会在 counterValue 每次变动时触发,确保 currentStep 始终匹配当前数值范围,这样数码表冠的步长就能实现动态切换了。

内容的提问来源于stack exchange,提问作者Bjorn Morrhaye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 16:53:10