Conditionally use VStack or HStack in SwiftUI
Evangelist Apps
Experts in mobile app Development & Design for all iOS (iPhones, iPads, Apple Watches & Apple TV) and Android platforms
By Atikur Rehman, Senior iOS Developer at Evangelist Apps
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.