Serhii Didanov
Serhii Didanov

Reputation: 2338

SwiftUI full screen transparent button

I try to add full screen transparent button:

Button(action: {
       // my action
}) {
    Rectangle()
     .opacity(0)
}

But in case .opacity() is less than 0.1 button action stop working. How to implement full screen transparent button?

Tested on iOS 14.3(Sim), iOS 14.2(iPhone X), Xcode 12.3

Upvotes: 6

Views: 2201

Answers (2)

Michiel Dral
Michiel Dral

Reputation: 4067

For me the .contentShape didn't work. At least, it didn't prevent the view behind my button to also receive the touch. But, and I feel dirty for suggesting this:

Button(action: {
    print("Yeahhh")
}) {
  Text("Yeah?").padding(64)
}
.background(LinearGradient(colors: [Color.clear], startPoint: .top, endPoint: .bottom))

Adding a transparent LinearGradient did the trick for me.

Upvotes: 1

Asperi
Asperi

Reputation: 257693

Here is possible solution. Tested with Xcode 12.1 / iOS 14.1

struct DemoClearButton: View {
    var body: some View {
        Color.clear
            .contentShape(Rectangle())
            .onTapGesture {
                print(">> transparent tapped")
            }
    }
}

Note: probably in place of usage you'd wanted to add .edgesIgnoringSafeArea(.all)

Upvotes: 7

Related Questions