On this part, we’re going to full the toggle view and animate it. Begin with including the next fixed variables that will likely be handed from our ContentView:
width
: the toggle view’s width.top
: the toggle view’s top.toggleWidthOffset
: the width of theroundedRectangle
that can act as our toggle swap.cornerRadius
: to customise the roundness of all of our rounded rectangles.padding
: to customise the match of our toggle swap inside our concave view.isToggled
: to change our toggle from on to off and vice versa.switchWidth
: to animate the motion of our toggle swap by stretching it.
In a ZStack, add one in all our concave views. Subsequent, you’ll be able to add “on” and “off” textual content in an HStack
, or add symbols as an alternative.
For the toggle’s swap, add a rounded rectangle with a body equal or to smaller than our toggle’s top. You need to use onAppear
to find out the switchWidth
measurement. Add shadows to the rounded rectangle to make it convex.
In .onTapGesture()
change the values of isToggled
to the alternative, and animate the switchWidth
twice. This can make the swap stretch, then get again to its measurement when the second animation finish.
To maneuver the swap from the left to the fitting and vice versa, add Spacer()
managed by isToggled
worth. Lastly, add animation( .spring)
to the roundedRectangle
.