0

I use this great code to get a slider. here

but how can i set the max value to 30 not to 100?

this example is from 0 to 100.

hope everyone can help.

struct CustomView: View {

@Binding var percentage: Float // or some value binded

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

}

xyzcodeeee
  • 161
  • 2
  • 13

1 Answers1

1

You just need to replace the 100 with 30 to get bound from 0 to 30


struct CustomView: View {

    @Binding var percentage: Float // or some value binded

    var body: some View {
        GeometryReader { geometry in
            ZStack(alignment: .leading) {
                Rectangle()
                    .foregroundColor(.gray)
                Rectangle()
                    .foregroundColor(.accentColor)
                    .frame(width: geometry.size.width * CGFloat(self.percentage / 30))
            }
            .cornerRadius(12)
            .gesture(DragGesture(minimumDistance: 0)
            .onChanged({ value in
                self.percentage = min(max(0, Float(value.location.x / geometry.size.width * 30)), 30)
                print(self.percentage)
            }))
        }
    }
}
Mac3n
  • 4,189
  • 3
  • 16
  • 29
  • and the rectangle needs to go to 100% not just to 30% – xyzcodeeee Mar 04 '20 at 20:25
  • you can set `frame` for your view rectangle, in this way the maximum value is 30 not affect the size of rectangle. ` CustomView(percentage: $percentage) .accentColor(.red) .frame(width: 300, height: 44)` – Mac3n Mar 04 '20 at 20:35
  • @Mac3n if i want to be between 0 and 1 should change 30 to 1 ? – Amin Rezaew Sep 06 '22 at 11:11