How to return VStack or HStack in SwiftUI

Issue #613

struct VOrH<Content>: View where Content: View {
    let isVertical: Bool
    let content: () -> Content

    init(isVertical: Bool, @ViewBuilder content: @escaping () -> Content) {
        self.isVertical = isVertical
        self.content = content
    }

    var body: some View {
        makeContent()
    }

    private func makeContent() -> some View {
        if isVertical {
            return VStack(spacing: 0) {
                content()
            }.eraseToAnyView()
        } else {
            return HStack(spacing: 0) {
                content()
            }.eraseToAnyView()
        }
    }
}
Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation