Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a slider in SwiftUI for an Int-type property?

Tags:

swiftui

slider

I have a view with with an Int property named "score" that I want to adjust with a slider.

struct IntSlider: View {
    @State var score:Int = 0

    var body: some View {
        VStack{
            Text(score.description)
            Slider(value: $score, in: 0.0...10.0, step: 1.0)
        }
    }
}

But SwiftUI's Slider only works with doubles/floats.

How can I make it work with my integer?

like image 756
Melodius Avatar asked Dec 14 '22 07:12

Melodius


1 Answers

struct IntSlider: View {
    @State var score: Int = 0
    var intProxy: Binding<Double>{
        Binding<Double>(get: {
            //returns the score as a Double
            return Double(score)
        }, set: {
            //rounds the double to an Int
            print($0.description)
            score = Int($0)
        })
    }
    var body: some View {
        VStack{
            Text(score.description)
            Slider(value: intProxy , in: 0.0...10.0, step: 1.0, onEditingChanged: {_ in
                print(score.description)
            })
        }
    }
}
like image 109
lorem ipsum Avatar answered Feb 03 '23 09:02

lorem ipsum