Now let’s start to add the dragging logic. Let’s start to do this by adding a gesture. Inside, we will add a DragGesture with a minimum distance of 0.

When we put our finger down on the knob, we want to save the position so we can refer to it later.

We can do this by checking if the person if is dragging by checking if the translation is greater than a small value eg. 0.1. Create a state to store the last offset then add this to the drag gesture:

Now we need to calculate what the new position of the knob should be.

We need to make sure it’s not able to go past the limits of the track, we can use max() and min() to do this. We can first make it not be able to go past the leading(left) part of the track. We will return the max value of either 6 or the translation that we have made. 6 is because we want the 6 padding on the side or else we will be able to move the knob back to 0 offset without padding.

The translation will be the current translation plus what the previous offset was.

Our slider not only looks like a slider, but is now starting to act like one!

We can see that what we have done works, but it is still able to go over the trailing(right) side of the track, lets fix this. We used max() for the leading so we’re going to use min() for the trailing.

First we need to know how big our slider actually is, to know this, we have to embed our view in a GeometryReader. GeometryReader gives us lots of information about the views frame size and more. We want to know what the width of the frame is minus the leading and minus the trailing offset (which will be 12).

Try doing this:

You will notice that due to being in a closure, any variables or constants outside GeometryReader will need to be marked with “self.”.