Search code examples
iosswiftswiftuislider

Customize Number in Custom Picker so that it's a Multiplier of 5


I used a code from here, and I want to make it so that the custom slider only represents a number that is a multiplier of 5 in the range 5 to 180. I am using SwiftUI in XCode 12.5, and here is the code. PS. This is not the entire code, but I want the code to be in proximity to this code.

CustomSlider(value: $someValue, range: 5...180)

Solution

  • Method 1

    The first method is to round the value of someValue to the nearest 5 every time it changes. The slider can only go up in fixed increments, so it does look a bit jumpy.

    Code:

    struct ContentView: View {
        @State private var someValue: CGFloat = 5
    
        var body: some View {
            VStack {
                CustomSlider(value: $someValue, range: 5 ... 180)
    
                Text("Value: \(someValue)")
            }
            .onChange(of: someValue) { newValue in
                someValue = round(newValue / 5) * 5
            }
        }
    }
    

    Method 2

    This method the slider is continuous, but the values you read from sliderValue is rounded to the nearest 5. I prefer this method as it feels smoother.

    Code:

    struct ContentView: View {
        @State private var someValue: CGFloat = 5
        private var sliderValue: CGFloat {
            round(someValue / 5) * 5
        }
    
        var body: some View {
            VStack {
                CustomSlider(value: $someValue, range: 5 ... 180)
    
                Text("Value: \(sliderValue)")
            }
        }
    }