我有一个视图,通过更新其位置在屏幕上拖动。我很难通过参数设置它的初始位置。
我试图使用注释掉的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)
}
}
}
可以在view的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 !!
}
// ...
}
您可以使用GeometryReader
来读取View
的frame
,得到其center
&赋值给initialPosition
.
试试这个:
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
}
}
}
}
}