Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make SwiftUI tap not extend beyond bounds when clipped

Tags:

ios

swift

swiftui

Tap registering beyond clipped view bounds.

It seems SwiftUI will layout an image in its full width and height inside of another view to give it a fill mode of aspect fill. That is fine but if I want to add a tap action to the view the tap registers outside the bounds of the view even when clipped. I may be doing this wrong or there may be another way. In addition to this code I have tried using .clippedShape and .contentShape of rectangle. How do I get it to where taps outside the clipped frame do not register on the underlying image. To reproduce switch to clip and tap in the area the image would occupy outside the frame of the clipped view.

import SwiftUI

struct ImageContainer : View {
    var body: some View {
        Image(systemName: "cube")
        .resizable()
        .scaledToFill()
        .clipped()
    }
}

struct ContentView: View {
    @State var isClipped = false
    @State var count = 0

    var body: some View {
        VStack{
            Toggle(isOn: $isClipped) {
                Text("Clip It ")
                .font(.title)
            }.frame(width: 175)
            ZStack{
                if self.isClipped == true{
                    ImageContainer()
                        .frame(width: 200, height: 200)
                        .contentShape(Rectangle())
                        .clipped()

                        .background(Color.blue)
                        .onTapGesture {
                            print("tapped mainContainer\(self.count)\n")
                            self.count += 1
                        }
                }else{
                    ImageContainer()
                        .frame(width: 200, height: 200)
                        .background(Color.blue)
                         .onTapGesture {
                            print("tapped mainContainer\(self.count)\n")
                            self.count += 1
                    }
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
like image 866
agibson007 Avatar asked Aug 27 '19 12:08

agibson007


1 Answers

I've had success using .contentShape(Rectangle()) on the image which controls the tappable area.

You can try using ZIndex so surrounding views capture the hit. But I have had mixed results with that, AFAIK that's buggged too as of iOS 14.1

like image 61
Miguel Lomelí Avatar answered Sep 22 '22 08:09

Miguel Lomelí