How to divide HStack into two equal parts and place image in the middle of each part?

Viewed 371

I want to conditionally divide HStack into two equal parts and place a circle in the middle of each part, how can this be done?

struct ContentView: View {
    
    var body: some View {
        Form{
            HStack{
                Image(systemName: "circle.fill")
                Image(systemName: "circle.fill")
            }
        }
    }
}

As it is

That is how it should be

2 Answers

One way to do it is to give the Images a frame with maxWidth: .infinity. This will cause them to expand to fill the space:

struct ContentView: View {
    
    var body: some View {
        Form{
            HStack{
                Image(systemName: "circle.fill").frame(maxWidth: .infinity)
                Image(systemName: "circle.fill").frame(maxWidth: .infinity)
            }
        }
    }
}

demo running in Preview

We can use two transparent colors that fill equally available space and put images into overlay, which uses centred default layout, like

enter image description here

var body: some View {
    Form{
        HStack{
            Color.clear.overlay(Image(systemName: "circle.fill"))
            Color.clear.overlay(Image(systemName: "circle.fill"))
        }
    }
}
Related