Search code examples
xcodeimageswiftuiclippednavigationlink

Clip clickable parts of image as NavigationLink (SwiftUI)


When implementing an image in a NavigationLink closure and clipping that image, the unclipped image is clickable. Because of the clipping, the images are overlapping each other (see attached screenshots). Overlapping Images Clipped Images The first screenshot shows the original size. When clipped (second screenshot) clicking on the red hatched area (shown in the first screenshot), the second NavigationLink is triggered, not the first one.

The following code produces the problem:

var body: some View {
        NavigationView{
            ScrollView{
                VStack (spacing: 20) {
                    NavigationLink(destination: ImageGalleryView1()) {
                        Image(uiImage: downsample(imageAt: URL(string: "imageURL")!, to: CGSize(width: 500, height: 500), scale: 1))
                            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 200, alignment: .center)
                            .clipped()
                    }
                    NavigationLink(destination: ImageGalleryView2()) {
                        Image(uiImage: downsample(imageAt: URL(string: "imageURL")!, to: CGSize(width: 500, height: 500), scale: 1))
                            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 200, alignment: .center)
                            .clipped()
                    }
                    NavigationLink(destination: ImageGalleryView3()) {
                        Image(uiImage: downsample(imageAt: URL(string: "imageURL")!, to: CGSize(width: 500, height: 500), scale: 1))
                            .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: 200, alignment: .center)
                            .clipped()
                    }
               }
          }
}

I tried to clip the Image, tried to clip the NavigationLink, played around with the .frame()-properties. But with no success.

My aim is to create a VStack with three images where each of them is a NavigationLink. The clipped parts shouldn't be clickable. I want to avoid buttons or shapes in this case, if possible.


Solution

  • I don't know your exact implemetation of downsample(imageAt:), but the implementation below gets rid of the overlapping of images:

    NavigationLink(destination: ImageGalleryView1()) {
                        Image("sample-image")
                        .resizable(resizingMode: .tile)
                        .frame(minWidth: 0,
                               maxWidth: .infinity,
                               minHeight: 0,
                               maxHeight: 200,
                               alignment: .center)
                    }