Last active
February 20, 2024 19:07
-
-
Save laszlotuss/dd6e87f6ce79419d74a3ac1a0c736f1b to your computer and use it in GitHub Desktop.
AdaptiveStack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftUI | |
struct AdaptiveStack<Content: View>: View { | |
@Environment(\.horizontalSizeClass) var sizeClass | |
let horizontalAlignment: HorizontalAlignment | |
let verticalAlignment: VerticalAlignment | |
let spacing: CGFloat? | |
let isVertical: Bool? | |
let content: () -> Content | |
init(isVertical: Bool?, horizontalAlignment: HorizontalAlignment = .center, verticalAlignment: VerticalAlignment = .center, spacing: CGFloat? = nil, @ViewBuilder content: @escaping () -> Content) { | |
self.isVertical = isVertical | |
self.horizontalAlignment = horizontalAlignment | |
self.verticalAlignment = verticalAlignment | |
self.spacing = spacing | |
self.content = content | |
} | |
var body: some View { | |
Group { | |
if isVertical ?? (sizeClass == .compact) { | |
VStack(alignment: horizontalAlignment, spacing: spacing, content: content) | |
} else { | |
HStack(alignment: verticalAlignment, spacing: spacing, content: content) | |
} | |
} | |
} | |
} | |
#Preview { | |
AdaptiveStack(isVertical: true) { | |
Text("Horizontal when there's lots of space") | |
Text("but") | |
Text("Vertical when space is restricted") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment