Conditionally use VStack or HStack in SwiftUI

Atikur Rahman
Evangelist Apps Blog
May 23, 2022
Photo credits Unknown

In your SwiftUI app, there might be cases where you might want to stack some views horizontally or vertically based on certain conditions or even while rotating the device. While we can use a condition to wrap the views in either VStack or HStack.

The above approach is not ideal and leads to code duplication (as you notice above).

A better solution would be to create an AdaptiveStack view, which accepts a boolean parameter to decide whether to stack the child views horizontally or vertically.

Then we could we that AdaptiveStack view as below -

Please share your thoughts and suggestions on this article.

Keep up with us on social media:

LinkedIn : https://www.linkedin.com/company/evangelist-apps-limited/

Twitter : https://twitter.com/EvangelistSW/

--

--