Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clipped Image calls TapAction outside frame

I have a issue concerning the tapAction on a image. The TapAction closure gets called on the clipped area which shouldn't happen. What should I do?

Image(uiImage: image)
    .resizable()
    .aspectRatio(contentMode: .fill)
    .frame(height: 200, alignment: .center)
    .presentation(tapped ? Modal(Image(uiImage: image)) : nil)
    .clipped()
    .cornerRadius(10)
    .border(Color.black, width: 2, cornerRadius: 10)
    .tapAction {
        self.tapped.toggle()
    }

That's the result:

enter image description here

like image 290
SwiftiSwift Avatar asked Jul 12 '19 20:07

SwiftiSwift


1 Answers

Update

I updated my answer. This is the proper way of doing it. There is a modifier called contentShape() that you can use to define the hit test area:

import SwiftUI

struct ContentView: View {
    @State private var tapped = false

    var body: some View {
        Image(systemName: "circle.fill")
            .resizable()
            .aspectRatio(contentMode: .fill)
            .frame(height: 200, alignment: .center)
            .presentation(tapped ? Modal(Image(systemName: "photo")) : nil)
            .clipped()
            .cornerRadius(10)
            .border(Color.black, width: 2, cornerRadius: 10)
            .contentShape(TapShape())
            .tapAction {
                self.tapped.toggle()
            }
    }

    struct TapShape : Shape {
        func path(in rect: CGRect) -> Path {
            return Path(CGRect(x: 0, y: 0, width: rect.width, height: 200))
        }
    }
}
like image 146
kontiki Avatar answered Nov 19 '22 07:11

kontiki