问题描述
在学习SwiftUI
的过程中,我遇到了这个问题.
In the process of learning SwiftUI
, I am having this issue.
我有一个带有滑块的视图:
I have this view with a slider:
struct RangeSpanView: View {
var minimumValue,maximumValue:Double
init(minSlide: UInt64,
maxSlide: UInt64) {
self.minimumValue = Double(minSlide)
self.maximumValue = Double(maxSlide)
}
@State var sliderValue = 0.0
var body: some View {
VStack {
HStack {
Text("\(Int(minimumValue))")
Slider(value: $sliderValue,
in: minimumValue...maximumValue)
Text("\(Int(maximumValue))")
}.padding()
Text("\(Int(sliderValue))")
Spacer()
}
}
}
这是加载视图的代码.
var body: some View {
NavigationLink(destination: RangeSpanView(minSlide: myMinVal,
maxSlide: myMaxVal),
label: {
.......... // Useful code.
})
}
使用滑块可以正常工作.关于 sliderValue 的初始化,我只想修复一些不一致的细节.
It works fine using the slider. There is only a little inconsistency detail concerning the initialization of the sliderValue that I would like to fix.
当前代码的方式是将 sliderValue 初始化为 0.0,当最小值和最大值分别为 150.0 和 967.0(例如)时,这不是我喜欢的.
The way it is in the current code is that sliderValue is initialized to 0.0, which is not exactly what I like when the min and max values are respectively 150.0 and 967.0 (for example).
我尝试了各种解决方案来将 sliderValue 初始化为 minimumValue(例如)以使其一致.但它总是失败,并出现一些错误消息,抱怨某些预期的参数类型‘绑定’".在 Slider
对象中.
I have tried various solutions to initialize sliderValue to minimumValue (for example) to make it consistent. But it always fails with some error message complaining about some "expected argument type 'Binding" in the Slider
object.
那么,有没有合适的方法来解决这个问题?
So, is there a proper way to solve this problem?
推荐答案
您可以使用滑块的最低最小值初始化 @State 变量.因此,您无需在 willApear() 方法中执行此操作.
You can initialize your @State variable with the lowest min value of the slider. So you won't need to do this in the willApear() method.
struct RangeSpanView: View {
var minimumValue,maximumValue:Double
//declare State here
@State var sliderValue : Double
init(minSlide: UInt64,
maxSlide: UInt64) {
self.minimumValue = Double(minSlide)
self.maximumValue = Double(maxSlide)
//Initialize the State with the lowest value
self._sliderValue = State(initialValue: self.minimumValue)
}
这篇关于在 SwiftUI 中初始化 Slider 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!