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
相关产品推荐
相关产品推荐

