问题描述
我正在制作“范围”滑块-带有两个拇指的Slider
代表年龄范围。
这些值绑定到它们相应的UserDefaults
值(使用SwiftUI的AppStorage
包装器)。
当我拖动拇指时,它将根据其新的UserDefaults
坐标更新其position.location.x
值。
这是视图:
struct AgeSlider : View {
@AppStorage("minAge") var minAge: Double = 18
@AppStorage("maxAge") var maxAge: Double = 65
@State var leftThumbMoving = false
@State var rightThumbMoving = false
var body: some View {
GeometryReader { geo in
ZStack{
Color.gray.opacity(0.4)
.frame(minWidth: 0,maxWidth: .infinity,minHeight: 0,maxHeight: 2,alignment: .center)
.onAppear {
print("width: \(geo.frame(in: CoordinateSpace.local).width)")
}
HStack{
Circle()
.foregroundColor(leftThumbMoving ? Color.orange.opacity(0.5) : Color.orange)
.position(x: CGFloat(self.minAge),y: 0)
.frame(width: 25,height: 25)
.offset(x: 0,y: 15)
.gesture(
DragGesture()
.onChanged { position in
self.leftThumbMoving = true
UserDefaults.standard.set(position.location.x,forKey: "minAge")
print("x: \(position.location.x)")
}
.onEnded { position in
self.leftThumbMoving = false
}
)
.onAppear {
print("width: \(geo.frame(in: CoordinateSpace.local).width)")
}
Circle()
.foregroundColor(rightThumbMoving ? Color.orange.opacity(0.5) : Color.orange)
.position(x: CGFloat(self.maxAge),y: 15)
.gesture(
DragGesture()
.onChanged { position in
self.rightThumbMoving = true
UserDefaults.standard.set(position.location.x,forKey: "maxAge")
}
.onEnded { position in
self.rightThumbMoving = false
}
)
}
}
}
}
}
我正在尝试下一步,即调整公式,以使滑块的范围在18到65之间。
但是,随机x
值给我带来了麻烦。举个例子,下面的第一个橙色拇指的x
值为-130
:
这个负值到底是哪里来的?
第二个拇指值是60
。
如果您好奇的话,这里是父视图:
struct Settings: View {
let auth: UserAuth
init(auth: UserAuth) {
self.auth = auth
}
@AppStorage("minAge") var minAge: Double = 18
@AppStorage("maxAge") var maxAge: Double = 65
@State var showDeleteDialog = false
@State var deleteText: String = ""
var body: some View {
NavigationView {
Form {
Section {
Text(String(Int(minAge))).foregroundColor(.orange)
}
Section {
Text("Max age")
AgeSlider()
Text(String(Int(maxAge))).foregroundColor(.orange)
}
Section {
Text("Details")
Text("Gender: \(UserDefaults.standard.string(forKey: "gender")?.capitalizingFirstLetter() ?? "UnkNown")").foregroundColor(.gray)
Text("Birthday: \(UserDefaults.standard.string(forKey: "birthday") ?? "UnkNown")").foregroundColor(.gray)
}
Section {
Text("Account")
Button(action: { self.auth.goOffline() }){
Text("logout")
}
NavigationLink(destination: DeleteAccount(auth: self.auth)){
Text("Delete Account")
}
}
}.navigationBarTitle(Text("Settings")).accentColor(Color.orange)
}.accentColor(.black)
}
}
解决方法
问题出在ZStack
上,它失去了子元素的x
值。
通过删除父ZStack
-子x
的值将从0开始。
但是,如果您需要保留ZStack
,则可以选择以下替代方法:
ZStack(alignment: .leading)
-因此,x
值从ZStack
容器的左侧开始。