Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Align HStack with different size elements

Tags:

swift

swiftui

I am looking to build an HStack that has 3 elements in it, one to the left, one in the middle and one to the right. The middle element should always be in the centre, but because the left and right elements are dynamic and so can be different lengths the middle element is getting pushed depending on the size of the side elements (see picture below). I am using spacers and padding, but need something that will auto adjust the size of the spacers. Does anyone know of a way to do this?

See code attached below:

VStack(alignment: .leading){
                    Text(item.itemName)
                        .padding(1)
                        .padding(.horizontal, 20)
                    
                    HStack{
                        //Representative item code
                        Text("123454")
                            .padding(.horizontal, 20)
                        Spacer()
                        
                        Text(item.itemQuantity)
                            //.position(x: 100)

                        Spacer()
                        Text(item.itemPrice)
                            .padding(.horizontal, 20)
                    }

                }

Image showing unaligned hstack items

like image 995
mdav132 Avatar asked Sep 11 '25 01:09

mdav132


1 Answers

You can set the left and right views to fill as much width as possible. This will make them both evenly split up the space, excluding the middle Text.

To achieve this, you set the maxWidth to .infinity, and then align them to the correct side.

You tried to use Spacer(), which made the Spacers have equal width. However, with this solution, you are making these views have equal width.

Example:

struct ContentView: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text("Puma Buckett Hat")

            HStack(spacing: 0) {
                Text("123454").frame(maxWidth: .infinity, alignment: .leading)

                Text("1")

                Text("35.99").frame(maxWidth: .infinity, alignment: .trailing)
            }
        }
        .padding()
    }
}

Result:

Result

Adding border to each element in HStack to show how the space is taken up:

Result 2

And what it looks like when you have multiple of these:

Result 3

like image 181
George Avatar answered Sep 13 '25 16:09

George