How to Dynamically Change Between Vstack and Hstack

What’s New in iOS 16?

June 01, 2022 — The AnyLayout struct in SwiftUI gives us the ability to easily transition between HStack and VStack, and this may be done based on any environment context that we choose to take into account.

How To Have The Hstack And Vstack Stacks Automatically Exchange Places Based On The Size Class

SwiftUI enables us to monitor the current size class in order to determine how things should be laid out. For instance, when there is an abundance of room, we can go from an HStack to a VStack, but when space is limited, we can stick with an HStack.

We just need to put some thought into it, and we can come up with an alternative AdaptiveStack view that will handle the switching for us between vertical and horizontal layouts automatically. Because of this, it is now much simpler to create wonderful layouts on an iPad since our layouts will now automatically alter to accommodate slipover scenarios and split views.

You can test it out by running the application in an iPad simulation model and experimenting with different split-view sizes. When the space available on the screen becomes limited, ContentView will automatically transition to a VStack.

Now, let’s go over the operation of the custom view:

It keeps an eye on the horizontal Size Class environment key and ensures that it is always brought up to date whenever the size class is modified.

We have provided it with settings to store vertical and horizontal alignment separately, allowing you to have complete control over how the layout should adjust to its environment.

Because VStack and HStack operate with CGFloats, there is a CGFloat parameter that can be used for spacing if desired. You could add the horizontal spacing and vertical Spacing properties if you needed even more control over the formatting.

The view builder that end-users will count on to generate their layouts is going to be dependent on the content property, which is a function that does not accept any parameters but does return some kind of content.

Our initializer stores all of them aside for use at a later time.

Inside of the body property, we are able to read the horizontal size class and then enclose a call to content in either a VStack or an HStack, depending on our preferences.

And that wraps things up! The actual code is not quite as complicated as you might think, but it does provide us with a great deal of useful flexibility.

HostRooster is a leading web hosting solutions company. Since our founding in 2019, HostRooster has continually innovated new ways to deliver on our mission: to empower people to fully harness the web. Based in London, England, we provide comprehensive tools to users throughout the world so anyone, novice or pro, can get on the web and thrive with our web hosting packages.




%d bloggers like this: