SwiftUI里Slider用法示例

2,095 阅读1分钟

Slider用法示例

  1. isTracking指示用户是否在拖拽Slider, 在onEditingChanged的block里设置,防止拖拽的同时被Timer修改
  2. $processValue前面的$表示绑定
  3. in 后面跟Slider的范围
  4. Slider的label是显示不出来的,SwiftUI的bug
  5. specifier后面是字符串的格式,保留两位小数
  6. 想要在value值改变时做事情,重写 Bindingset,调用 sliderChanged
//
//  ContentView.swift
//  SliderDemo
//
//  Created by dacaiguoguo on 2021/7/5.
//

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…