Ovidiu Manea
Ovidiu Manea

Reputation: 1

OnTapGesture ALWAYS registers out of frame or view

I'm new to Swift, trying to do a personal project and I currently am stuck at a thing for which I cannot find a resolution anywhere for the past week.

This is the code:


import SwiftUI

struct MainStatsView: View {
    
    var stat: StatElements
    
    var body: some View {
        
        ZStack {
            
            Group {
                
                Image(stat.borderName)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: 90,
                           height: 90)
                    
                
                VStack {
                    Text(stat.statName)
                    Text("+" + String(stat.statModifier))
                    Text(String(stat.statValue))
                }
                .font(.caption)
            }
           
        }
        .frame(width: 90,
               height: 90)
        .contentShape(Rectangle())
        .clipped()
        .onTapGesture {
            print ("something")
        }
        
    }
}

struct MainStatsView_Previews: PreviewProvider {
    static var previews: some View {
        MainStatsView(stat: StatElements(statName: "test", statModifier: 2, statValue: 1) )
    }
}

And this is what it looks like:

preview

The issue is that no matter what I do, if I tap outside of the 90x90 image I've made, the OnTapGesture function registers for probably about 10 more pixels. Same thing happens if I put it on the VStack, which simply is as large as the text, effectively spanning between the two "t"'s in "test", it behaves exactly the same, meaning if I click outside of the VStack it still registers.

I have tried to use .contentShape(Rectangle()), .clipped(), and to place the OnTapGesture function virtually everywhere in the code, just to see how it behaves. Strangely, .contentShape and .clipped() don't seem to do absolutely anything. I've tried to put them everywhere as well, on the parent ZStack, on the Group and on the VStack, to see what happens. I don't know what I'm doing wrong, I thought I understand how modifiers sort of work but apparently not and it feels like I'm just trying to randomly attach modifiers to views, hoping that maybe there's a winning combination.

Edit: added a small gif.

Registered Clicks

Upvotes: 0

Views: 190

Answers (0)

Related Questions