本文介绍了SwiftUI 中步进器的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在手动(非绑定)模式下使用 onIncrement 和 onDecrement 使用 Stepper 视图.当我尝试实现下限和上限时,有一种奇怪的行为,例如.年龄值不低于 1 或高于 10.

I want to use the Stepper view in manual (not binding) mode using onIncrement and onDecrement. There's a strange behavior when I try to implement lower and upper bounds, eg. having an age value not going bellow 1 or above 10.

如果你尝试下面的代码,你可以在它已经有值1"后按两次-".它并没有像预期的那样低于 1,但是在两次额外按下后,-"按钮突然被禁用.如果您然后按+",则没有任何反应.仅在另外按 2 次+"后,计数器才会按预期做出反应并变为 2.

If you try the bellow code, you can press "-" two times after it already has the value "1". It doesn't go bellow 1 as expected, but after the two additional presses the "-" button suddenly gets disabled. If you then press "+" nothing happens. Only after 2 additional presses to "+" the counter reacts as expected and goes to 2.

这是一个错误吗?

struct StepperTest: View {
    @State private var age = 5

    var body: some View {
        VStack {
            Stepper("Enter your age", onIncrement: {
                if self.age < 10 {
                    self.age += 1
                    print("Adding to age")
                }
            }, onDecrement: {
                guard self.age > 1 else { return }
                self.age -= 1
                print("Subtracting from age")
            })

            Text("Your age is \(age)")
        }
    }
}

推荐答案

在递增后检查和重置值似乎有效:

Checking and resetting the value after incrementing seems to work:

Stepper("Enter your age", onIncrement: {
                    self.age += 1
                    if self.age > 10 {self.age = 10}
                }
            }, onDecrement: {
                self.age -= 1
                if self.age < 1 {self.age = 1}
            })

这篇关于SwiftUI 中步进器的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:41