SwiftUI Spacer not working - The element isn't pushed to the end of the row

Viewed 286

I have a cell row which contains the following:

HStack {
    Text(self.category.name.capitalizingFirstLetter())
        .font(.body)
        .fontWeight(.light)
    Spacer()
        .background(Color.red)
    if category.id == selectedCategoryID {
        Circle()
            .foregroundColor(.pink)
            .background(Color.yellow)
    }
}

I am trying to have the Circle appear on the right side of the row and this is why I used the Spacer. This is how it actually looks like:

enter image description here

I added the background color for the circle and the spacer only for better visual of the situation.

Can anyone please help?

2 Answers

I assume you wanted this

demo

    Circle()
        .foregroundColor(.pink)
        .background(Color.yellow)
        .aspectRatio(contentMode: .fit)    // << here !!
        .fixedSize(horizontal: true, vertical: false) // << here !!

Right now, the Circle view is taking up the entirety of the horizontal and vertical space, even though what is actually rendered as the circle is only shown in a small part (you can visualize this more clearly by adding a .border(Color.green) to the Circle view).

To fix this, you can use aspectRatio to make sure that the actual frame of the circle view stays a square (ie an aspect ratio of 1.0)

struct ContentView: View {
    var body: some View {
        HStack {
            Text("test")
                .font(.body)
                .fontWeight(.light)
            Spacer()
            Circle()
                       .foregroundColor(.pink)
                       .background(Color.yellow)
                       .aspectRatio(1.0, contentMode: .fit)
        }
        .frame(height: 100)
    }
}

It isn't immediately clear to me where you want the yellow background -- if you want it still taking up as much horizontal space as possible (but not under the text), you could use an additional HStack:

struct ContentView: View {
    var body: some View {
        HStack {
            Text("test")
                .font(.body)
                .fontWeight(.light)
            HStack {
                Spacer()
                Circle()
                  .foregroundColor(.pink)
                  .aspectRatio(1.0, contentMode: .fit)
            }
            .background(Color.yellow)
        }
        .frame(height: 100)
    }
}

enter image description here

Related