[英]Initial position of a SwiftUI view
I have a view that gets dragged around the screen by updating its position.我有一个通过更新其位置在屏幕上拖动的视图。 I'm having a hard time setting its initial position via an argument.
我很难通过参数设置其初始位置。
I'm trying to use the commented out var initialPosition argument.我正在尝试使用注释掉的var initialPosition参数。
struct FloatingView<Content:View>: View {
let content: Content
var hidden: Bool
var size: CGSize
// var initialPosition: CGPoint
@State private var location: CGPoint = CGPoint(x:65, y:100)
var simpleDrag: some Gesture {
DragGesture()
.onChanged { value in
self.location = value.location
}
}
var body: some View {
if hidden == false {
content
.foregroundColor(.pink)
// .frame(width: 100, height: 100)
.position(location)
.gesture(simpleDrag)
}
}
}
You could use a GeometryReader
in order to read the frame
of the View
, get its center
& assign it to initialPosition
.您可以使用
GeometryReader
来读取View
的frame
,获取其center
并将其分配给initialPosition
。
Try this:尝试这个:
struct FloatingView<Content:View>: View {
let content: Content
var hidden: Bool
var size: CGSize
@State var initialPosition: CGPoint
@State private var location: CGPoint = CGPoint(x:65, y:100)
var simpleDrag: some Gesture {
DragGesture()
.onChanged { value in
self.location = value.location
}
}
var body: some View {
GeometryReader { proxy in
if hidden == false {
content
.foregroundColor(.pink)
//.frame(width: 100, height: 100)
.position(location)
.gesture(simpleDrag)
.onAppear {
initialPosition = proxy.frame(in: .global).center
}
}
}
}
}
It is possible to do this in view's init, like可以在视图的 init 中执行此操作,例如
struct FloatingView<Content:View>: View {
private let content: Content
private let hidden: Bool
private let size: CGSize
@State private var location: CGPoint
init(content: Content, hidden: Bool, size: CGSize, initialPosition: CGPoint) {
self.content = content
self.hidden = hidden
self.size = size
self._location = State(initialValue: initialPosition) // << here !!
}
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.