Skip to content

Instantly share code, notes, and snippets.

@laszlotuss
Last active February 20, 2024 19:07
Show Gist options
  • Save laszlotuss/dd6e87f6ce79419d74a3ac1a0c736f1b to your computer and use it in GitHub Desktop.
Save laszlotuss/dd6e87f6ce79419d74a3ac1a0c736f1b to your computer and use it in GitHub Desktop.
AdaptiveStack
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