Stepper
概述
Stepper 是一个用于递增或递减值的控件。它由"+“和”-“两个按钮组成,用户可以通过点击来增加或减少数值。常用于选择数量、调整数值等场景。
1struct Stepper<Label> where Label : View
创建 Stepper
基本用法
使用字符串作为标题创建 Stepper:
1@State private var age = 18
2
3Stepper("Enter your age", value: $age, in: 0...130)
使用自定义标签作为标题创建 Stepper:
1@State private var quantity = 1
2
3Stepper(value: $quantity, in: 1...10) {
4 Text("数量: \(quantity)")
5}
自定义步长
使用 step 参数自定义每次递增/递减的数值:
1Stepper(value: $value, in: 0...100, step: 5) {
2 Text("值: \(value)")
3}
使用 onIncrement 和 onDecrement
使用 onIncrement 和 onDecrement 闭包自定义递增/递减逻辑:
1@State private var value = 5
2
3Section("自定义递增/递减逻辑") {
4 Stepper {
5 Text("值: \(value)")
6 } onIncrement: {
7 value = min(value * 2, 100)
8 } onDecrement: {
9 value = max(value / 2, 1)
10 }
11}
带有编辑状态回调
使用 onEditingChanged 监听编辑状态变化:
1@State private var isEditing = false
2
3Stepper(value: $value, in: 0...100) { editing in
4 isEditing = editing
5 print("正在编辑: \(editing)")
6}
带有格式化的 Stepper
使用 format 参数自定义数值显示格式:
1@State private var temperature = 20.0
2
3Stepper(value: $temperature, in: 10...40, step: 0.5, format: .number.precision(.fractionLength(1))) {
4 Text("温度")
5}
修饰符
labelsHidden
隐藏 Stepper 的标签:
1Stepper("标签", value: $value, in: 0...10)
2 .labelsHidden()
foregroundStyle
修改 Stepper 标题的颜色:
1Stepper("标题", value: $value, in: 0...10)
2 .foregroundStyle(.cyan)
完整示例
1import SwiftUI
2
3struct StepperDemo: View {
4 @State private var quantity = 1
5 @State private var brightness = 50.0
6 @State private var temperature = 20.0
7 @State private var value = 5
8
9 var body: some View {
10 Form {
11 Section("基础用法") {
12 Stepper(value: $quantity, in: 1...99) {
13 Text("数量: \(quantity)")
14 }
15 }
16
17 Section("自定义步长") {
18 Stepper(value: $brightness, in: 0...100, step: 5) {
19 HStack {
20 Text("亮度")
21 Spacer()
22 Text("\(Int(brightness))%")
23 }
24 }
25 }
26
27 Section("自定义递增/递减逻辑") {
28 Stepper {
29 Text("值: \(value)")
30 } onIncrement: {
31 value = min(value * 2, 100)
32 } onDecrement: {
33 value = max(value / 2, 1)
34 }
35 }
36
37 Section("隐藏标签") {
38 Stepper("标签", value: $quantity, in: 1...99)
39 .labelsHidden()
40 }
41
42 Section("自定义颜色") {
43 Stepper(value: $quantity, in: 1...99) {
44 Text("自定义颜色")
45 }
46 .foregroundStyle(.cyan)
47 }
48
49 Section("格式化数值") {
50 if #available(iOS 16.0, *) {
51 Stepper(value: $temperature, in: 10...35, step: 0.5, format: .number.precision(.fractionLength(1))) {
52 Text("温度: \(temperature, specifier: "%.1f")°C")
53 }
54 }
55 }
56 }
57 }
58}
平台支持
| № | 平台 | 最低版本 |
|---|---|---|
| 0 | iOS | 13.0+ |
| 1 | iPadOS | 13.0+ |
| 2 | macOS | 10.15+ |
| 3 | tvOS | 13.0+ |
| 4 | watchOS | 6.0+ |
| 5 | visionOS | 1.0+ |
相关类型
- StepperStyle - Stepper 的样式协议