预期功能:
- 点按即可添加圈子
- 按“下一步”创建新的“框架”
- 将圆圈拖到新位置
- 按“返回”将圆圈恢复到之前的位置
问题: 如上图,在最后部分,当我点击“返回”时,圆圈停留在拖动位置,而不是按预期还原。
例如,当我向 (0,0) 添加一个圆圈时,创建一个新框架,将圆圈拖动到新位置 (10, 10) 并点击“返回”,控制台打印“框架:0,位置 (0,0) ”。当我点击下一步时,它会打印“ Frame: 1, position (10,10) ”。并再次点击“返回”打印 (0,0)。但 Circle 位置不会更新。
我已经尝试为结构使用一个类,DraggableCircleModel
并在其位置上使用了@Published,但这似乎并不奏效。
我在下面提供了我的课程以提供更多背景信息。这也是我第二次在这里发布问题,所以任何改进我的问题的建议都将不胜感激。非常感谢!
返回和下一步按钮
Button(action: {
self.viewModel.goTo(arrangementIndex: self.viewModel.currentIndex - 1)
}) { Text("Back") }
Button(action: {
self.viewModel.goTo(arrangementIndex: self.viewModel.currentIndex + 1)
}) { Text("Next")}
用于呈现圆圈的视图:
struct DisplayView: View {
@ObservedObject var viewModel: ViewModel
var body: some View {
ZStack {
Rectangle()
.overlay(
TappableView { location in
self.viewModel.addCircle(at: location)
})
ForEach(self.viewModel.currentArrangement.circles, id: \.id) { circle in
return DraggableCircleView(viewModel: self.viewModel,
circleIndex: circle.circleIndex,
diameter: 50,
offset: circle.position)
}
}
}
}
DraggableCircle 视图的相关部分
struct DraggableCircleView: View {
init(viewModel: ViewModel, circleIndex: Int, diameter: CGFloat, offset: CGPoint) {
// Initialize
...
_viewState = /*State<CGSize>*/.init(initialValue: CGSize(width: offset.x, height: offset.y))
// **Debugging print statement**
print("\(self.viewModel.currentCircles.forEach{ print("Frame: \(self.viewModel.currentIndex), position \($0.position)") }) \n")
}
var body: some View {
let minimumLongPressDuration = 0.0
let longPressDrag = LongPressGesture(minimumDuration: minimumLongPressDuration)
.sequenced(before: DragGesture())
.updating($dragState) { value, state, transaction in
// Update circle position during drag
...
}
.onEnded { value in
guard case .second(true, let drag?) = value else { return }
// get updated position of circle after drag
...
self.viewModel.setPositionOfCircle(at: self.circleIndex, to: circlePosition)
}
return Circle()
// Styling omitted
...
.position(
x: viewState.width + dragState.translation.width,
y: viewState.height + dragState.translation.height
)
.gesture(longPressDrag)
}