Slider用法示例
isTracking
指示用户是否在拖拽Slider, 在onEditingChanged
的block里设置,防止拖拽的同时被Timer
修改
$processValue
前面的$
表示绑定
in
后面跟Slider的范围
- Slider的
label
是显示不出来的,SwiftUI的bug
specifier
后面是字符串的格式,保留两位小数
- 想要在
value
值改变时做事情,重写 Binding
的 set
,调用 sliderChanged
import SwiftUI
var isTracking:Bool = false
struct ContentView: View {
@State var processValue:CGFloat = 0
var body: some View {
VStack {
Slider(value: $processValue, in: 0 ... 100, label: {
Text("aValue")
})
Slider(value: $processValue, in: 0 ... 100) {
Label(
title: { Text("Label") },
icon: { Image(systemName: "star.fill") }
)
}
Slider(value: $processValue, in: 0 ... 100, step: 1, onEditingChanged: { isEditing in
debugPrint("isEditing: \(isEditing)")
isTracking = isEditing
}, minimumValueLabel: Text("0"), maximumValueLabel: Text("100")) {
Text("Hello, world!")
}
Text("Hello \(processValue, specifier: "%.2f")")
.padding()
Slider(value: Binding(get: {
processValue
}, set: { (newVal) in
processValue = newVal
sliderChanged()
}), in: 0 ... 100, step: 1, onEditingChanged: { isEditing in
debugPrint("isEditing: \(isEditing)")
isTracking = isEditing
})
}.onAppear() {
Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { atimer in
if !isTracking {
processValue += 1
if processValue > 100 {
processValue = 0
}
}
}
}
}
func sliderChanged() {
print("Slider value changed to \(processValue)")
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
developer.apple.com/tutorials/s…