Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align Items in swiftUI Stack Evenly

How can the items in a swiftUI Stack be aligned evenly to fill up all the available space? The first and last item should be straight at the beginning / end of the parent's Stack frame like so:

enter image description here

For those familiar with css, the desired behavior is equal to the css3 property display: flex; justify-content: space-between;.

like image 591
lenny Avatar asked Aug 11 '26 13:08

lenny


1 Answers

Here is a demo of possible approach. Prepared & tested with Xcode 12 / iOS 14.

demo

struct ItemView: View {
    let value: Int
    var body: some View {
        Text("Item\(value)")
            .padding()
            .background(Color.blue)
    }
}

struct JustifiedContainer<V: View>: View {
    let views: [V]
    
    init(_ views: V...) {
        self.views = views
    }

    init(_ views: [V]) {
        self.views = views
    }
    
    var body: some View {
        HStack {
            ForEach(views.indices, id: \.self) { i in
                views[i]
                if views.count > 1 && i < views.count - 1 {
                    Spacer()
                }
            }
        }
    }
}

struct Demo_Previews: PreviewProvider {
    static var previews: some View {
        VStack {
            JustifiedContainer(
                    ItemView(value: 1),
                    ItemView(value: 2),
                    ItemView(value: 3)
            )
            JustifiedContainer([
                    ItemView(value: 1),
                    ItemView(value: 2),
                    ItemView(value: 3),
                    ItemView(value: 4)
            ])
        }
    }
}
like image 88
Asperi Avatar answered Aug 14 '26 21:08

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!