Search code examples
iosswiftuihstack

Align images in HStack


I have the following code in SwiftUI:

  HStack(spacing: 0) {
        ForEach(images) { thumbImage in
            Image(uiImage: thumbImage.image)
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(width: 50, height: 50)
                .clipped()
        }
    }
    .frame(width: 330, alignment: .center)
    .clipped()

I see the following output:

enter image description here

Effectively, it is clipping content both left and right of the HStack. What I want is clipping to only happen on the right (trailing) side, not the left side. What is the right way of achieving it?


Solution

  • The .clipped() modifier only does anything (that is, it only clips content) if the content overflows the frame.

    In your example, you have an HStack with content that is quite wide. You are setting a .frame of width 330 on the HStack and then clipping to this frame.

    • By default, the alignment for .frame is .center, but you've even set center alignment explicitly. This is why, the content in the middle is being seen and the content at the sides is being clipped.

    • If you want to see the leading content, but clip the trailing content, try changing the alignment to .leading:

    HStack(spacing: 0) {
        // ...
    }
    .frame(width: 330, alignment: .leading) // 👈 HERE
    .clipped()