Drag view and move it is popular behavior on mobile devices and in SwiftUI is easy to implement.
The drag view gesture is a powerful thing in SwiftUI. You can do it on every view, in this example, there is a Text view.
Text(“Hello, world!”)
First, create a State property position that keeps information on how much view is moved related to its parent. You can read more about the position related to parents here.
@State private var position = CGPoint(x: 50, y: 50)
Next, use this position and .position view modifier for the Text view.
Text(“Hello, world!”)
.position(position)
The last step is to create a DragGesture inside .gesture view modifier.
Text(“Hello, world!”)
.position(position)
.gesture(
DragGesture()
.onChanged({ newValue in
self.position = newValue.location
})
)
Inside onChanged, you assign a new location to position State property. The rest of the animation, SwiftUI does for you.
If you’d like to move to the start position after the user stopped dragging, use onEnded on DragGesture and assign the value you want to position property. Use animation to make it smooth, more information about the view animation.
DragGesture()
.onChanged({ newValue in
self.position = newValue.location
})
.onEnded { _ in
withAnimation {
self.position = CGPoint(x: 50, y: 50)
}
}
)