Search code examples
iosswiftswiftuilazyvgrid

How to properly fit a filled Image in its bounds on SwiftUI?


I have to fix a problem with Images on SwiftUI. I currently have to fill the images I receive in a certain vertical container, which are the cells of a LazyVGrid, but the problem is that the tappable area expands over the designated one.

I used the Accessibility Inspector, and I found out that the area in excess is due the Images. (screenshot attached)

The code I'm using is something similar to the following:

Image(uiImage: image.image)
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(
        maxWidth: width,
        maxHeight: height
    )
    .clipped()

I thought that by having the frames and the clipped method I could get rid of this problem, but that's not the case unless I'm using some squared images. Any idea of what could work to fix this problem? Thanks!

enter image description here


Solution

  • Just add .contentShape(Rectangle()) at the bottom:

                Image(uiImage: image.image)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(
                        maxWidth: width,
                        maxHeight: height
                    )
                    .clipped()
                    .contentShape(Rectangle())    // <- Here!