Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is Text onTapGesture not working for widened frame in SwiftUI?

I have this testing file that is not working how I expect it to.

import SwiftUI

struct SwiftUIView: View {
    
    @State var boolTest = false
    
    var nums = ["1","2","3","4","5","6","7"]
    
    var body: some View {
        VStack {
            ForEach(nums, id: \.self) { num in
                Text("\(num)")
                    .frame(width: 400)
                    .font(.system(size: 70))
                    .foregroundColor(boolTest ? .red : .green)
                    .onTapGesture {
                        boolTest.toggle()
                    }
            }

        }
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}

When I tap on a number, the foreground color changes as expected. However, I want to be able to tap on the areas left and right of the Text("\(num)") so I expanded the frame modifier to test. However the color only changes when I tap directly on the number or text.

How do I tap on the space left or right of the number and have it change colors instead of it doing nothing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The system treats the "invisible" (ie doesn’t have visible drawn content) part of the view as unresponsive unless you set a contentShape on it.

//...
.frame(width: 400)
.contentShape(Rectangle())
//...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading