Why I cannot interact with transparent views (e.g. `Color.clear`)?

import SwiftUI
import PlaygroundSupport

struct ContentView: View {

    @State var count = 1

    var body: some View {
        VStack {
            Color.clear
                .onTapGesture {
                    count += 1
                }
            Text("Counter: \(count)")
        }
    }
}

PlaygroundPage.current.setLiveView(ContentView())

The above counter doesn't work for Color.clear in the playground app. However, if the Color.clear were replaced by any color that's not transparent (e.g. Color.red) it will work.

I don't understand why transparent views are not interactable like other views. Make transparent views interactable can be very useful (e.g. provide a larger tolerance space to let visually-small controls recognise gestures).

Accepted Reply

I've found the solution in Stack Overflow. It's because by default SwiftUI views with zero opacity doesn't have a content shape. Use .contentShape(Rectangle()) makes the view use the Rectangle content shape so it becomes tappable:

Color.clear
    .contentShape(Rectangle())
    .onTapGesture {
        counter += 1
    }

Replies

deleted

I've found the solution in Stack Overflow. It's because by default SwiftUI views with zero opacity doesn't have a content shape. Use .contentShape(Rectangle()) makes the view use the Rectangle content shape so it becomes tappable:

Color.clear
    .contentShape(Rectangle())
    .onTapGesture {
        counter += 1
    }