MobileEntityLogo.png

Hi.

Welcome to the best online resource for IOS & Android tutorials.

How to create draggable views with SwiftUI

How to create draggable views with SwiftUI

In this tutorial we create a rectangle that we can drag around the screen, and if you let go it will go back to its previous starting position.

Lets dive into the code


struct ContentView: View {

@State private var position:CGPoint = CGPoint(x: 0, y: 0)

var body: some View {

HStack {

Rectangle()

.position(position)

.foregroundColor(.red)

.frame(width: 200, height: 200, alignment: .center)

.shadow(color: .red, radius: 5, x: 3, y: 10)

.hoverEffect()

.gesture(

DragGesture()

.onChanged({ (gesture) in

position = gesture.location

})

.onEnded({ (gesture) in

position = gesture.startLocation

})

)

}

}

}

First on lines 14-19 we created a rectangle that has some shadow, and hover animations. Then we created the drag gestures starting on line 20. We used .gesture which is sort of like a gesture listener of sorts. Then inside of that we have a function call called DragGesture() this will listen for drag gestures of the parent view, in this case the rectangle is our parent view. Then we call a method .onChanged which updates every frame, and provides drag location among other drag properties, however we are only going to be using the location. We have a variable where we store the drag location on line 11. We need this variable so we can assign the drag location to our rectangle’s position on line 15. With this code you can run it and see how the rectangle follows your finger or pointer, however now we will make the rectangle return to its previous start position (The place you picked it up from). This location isn’t particularly accurate, however it is accurate enough for this tutorial. We now add the logic to return to its original position in the .onEnd method which has the same gesture variable as .onChanged except this time we will assign our start position to our position variable shown on line 26. That is it. You completed the tutorial, and can now create awesome drag and drop apps using SwiftUI! Happy coding!

How to store custom fonts in SwiftUI

How to store custom fonts in SwiftUI

How to take in closures as parameters in custom SwiftUI Views

How to take in closures as parameters in custom SwiftUI Views

0