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.

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