swiftuihstack

How do you subclass or otherwise conveniently compose the "initialization arguments" of a HStack?


Say we have

HStack(alignment: .top, spacing: 12) {
  blah
  blah
}
.frame(maxWidth: .infinity)
.background(.green)
.padding(EdgeInsets(top: 0, leading: 4, bottom: 0, trailing: 12))

How to compose that for use everywhere?

Can it be done?


Solution

  • You can write BlahStack like this:

    public struct BlahStack<Content: View>: View {
        let alignment: VerticalAlignment
        let spacing: CGFloat
        let content: Content
    
        public init(
            alignment: VerticalAlignment = .top,
            spacing: CGFloat = 12,
            @ViewBuilder _ content: () -> Content
        ) {
            self.alignment = alignment
            self.spacing = spacing
            self.content = content()
        }
    
        public var body: some View {
            HStack(alignment: alignment, spacing: spacing) {
                content
            }
            .frame(maxWidth: .infinity)
            .background(.green)
            .padding(EdgeInsets(top: 0, leading: 4, bottom: 0, trailing: 12))
        }
    }