Flexible Stack View in SwiftUI (VStack + HStack + ZStack in one)
The Stack
view is a flexible stack view that can be either a VStack
, HStack
, or ZStack
depending on the parameters that you provide to it.
SwiftyLaunch uses it to adapt layouts of a view depending on the current platform, like for the AIVisionExampleView
of AIKit
.
View declaration:
Stack.swift
public struct Stack<Content: View>: View {
public init(
_ stackType: StackType,
spacing: CGFloat? = nil,
@ViewBuilder content: @escaping () -> Content
) {
self.stackType = stackType
self.spacing = spacing
self.content = content
}
}
stackType
- The type of the stack view. Can be.vertical
,.horizontal
, or.zAxis
.spacing
- The spacing between the views in the stack.content
- The content of the stack view. (Implicitly passed SwiftUI closure)
Usage Example
From the AIVisionExampleView()
of AIKit
utilizing the Flexible Stack View, as well as the currentPlatform global variable:
AIVisionExampleView.swift
import SwiftUI
import SharedKit
// ...Other imports
struct AIVisionExampleView: View {
// ...
var body: some View {
// VStack on iPhone, HStack on iPad
// iPhone: Camera Feed on top, Shutter Button at the bottom
// iPad: Camera Feed on the left, Shutter Button on the right
Stack(currentPlatform == .phone ? .vertical : .horizontal, spacing: 25) {
CameraView()
// VStack on iPad, HStack on iPhone
Stack(currentPlatform == .phone ? .horizontal : .vertical) {
// ...Photos Picker Button
Button {
// ...
} label: {
Circle()
.fill(.white)
.frame(width: 75, height: 75)
}
.buttonStyle(ShutterButton())
// ... Selfie / Rear Camera Switch Button
}
}
}
}