如何在SwiftUI中为Int类型属性创建滑块?
我有一个名为“score”的 Int 属性的视图,我想用滑块调整它。
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)
}
}
}
但是 SwiftUI 的 Slider 仅适用于双打/浮动。
我怎样才能让它与我的整数一起工作?
回答
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)
})
}
}
}