SwiftUI 中Slider的使用

效果如下

import SwiftUI

struct ContentView: View {
   
    @State private var value = 0.0
    @State private var isEditing = false
    @State private var value1:Float = 0.0
    
    var body: some View {
        VStack {
            Text("滑块的值:\(value,specifier:"%.2f")")
                .foregroundColor(isEditing ? .red : .black)
            Slider(value: $value, in: 0...100, step: 1, onEditingChanged: { (isEditing) in
                self.isEditing = isEditing
            }, minimumValueLabel: Text("1"), maximumValueLabel: Text("100")) {
                Text("11")
            }
            .accentColor(.green)
            .border(Color.red)
            VolumnChangeSlider(percentage: $value1)
                .frame(height: 40)
                .padding(.horizontal)
        }
    }
}

struct VolumnChangeSlider: View{
    @Binding var percentage: Float
    var body: some View{
        GeometryReader { geometry in
            ZStack(alignment: .leading){
                Rectangle()
                    .foregroundColor(.gray)
                Rectangle()
                    .foregroundColor(.blue)
                    .frame(width: geometry.size.width * CGFloat(self.percentage / 100))
            }
            .cornerRadius(12)
            .gesture(DragGesture(minimumDistance: 0).onChanged({ val in
                self.percentage = min(max(0, Float(val.location.x/geometry.size.width*100)), 100)
            }))
        }
    }
    
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
posted @ 2021-07-20 15:25  我不爱吃鱼  阅读(487)  评论(0编辑  收藏  举报
Live2D