Fattie
Fattie

Reputation: 12621

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?

Upvotes: 1

Views: 49

Answers (1)

rob mayoff
rob mayoff

Reputation: 385600

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))
    }
}

Upvotes: 2

Related Questions