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.
Netooze® is a cloud platform, offering services from data centers globally. When developers can use the straightforward, economical cloud that they love, businesses expand more quickly. With predictable pricing, thorough documentation, and scalability to support business growth at any stage, Netooze® has the cloud computing services you need. Startups, enterprises, and government agencies can use Netooze® to lower costs, become more agile, and innovate faster.