Search code examples
swiftuialignmentswift5

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;.


Solution

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