Stepper in SwiftUI

147 阅读1分钟

Stepper在平时用到的不多, 但是也是一个很好用的组件,当你想实现点击加一减一时,Stepper将是你最好的选择

struct StepperSample: View {
    @State var value = 0
    let range = 0...10
    let step = 1
    
    var body: some View {
        VStack {
            Stepper(value: $value,
                    in: range,
                    step: step) {
                Text("Current: (value)")
            }
                    .padding(10)
        }
    }
}

上述代码即可实现加减操作。

其中:

  1. ranges 是一个范围,规定了上线和下线值

  2. step 指定步长,也就是每次加或减的大小。

image.png

实现一个点击Stepper,更改背景颜色的例子

let colors = [Color.red, Color.blue, Color.orange]
    @State var colorIndex = 0
    var body: some View {
        ZStack {
            //            Stepper(value: $value,
            //                    in: range,
            //                    step: step) {
            //                Text("Current: (value)")
            //            }
            //                    .padding(10)
            
            colors[colorIndex]
                .edgesIgnoringSafeArea(.all)
            
            Stepper(
                "Select a backgroundColor",
                onIncrement: incrementStep,
                onDecrement: decrementStep)
            .foregroundColor(Color.black)
            .font(.headline)
            .padding()
            .background(Color.white.cornerRadius(10))
            .padding(20)
        }
    }
    
    func incrementStep() {
        colorIndex += 1
        guard colorIndex < colors.count else {
            colorIndex = 0
            return
        }
    }
    
    func decrementStep() {
        colorIndex -= 1
        guard colorIndex > 0 else {
            colorIndex = colors.count - 1
            return
        }
    }

Stepper自带一个方法,可以接受加和减的不同方法。

public init(_
titleKey: LocalizedStringKey, 
onIncrement: (() -> Void)?, 
onDecrement: (() -> Void)?,
onEditingChanged: @escaping (Bool) -> Void 
= { _ in })

效果如下:

ezgif.com-video-to-gif.gif

以上就是Stepper的例子

大家有什么看法呢?欢迎留言讨论。
公众号:RobotPBQ