Cesare
Cesare

Reputation: 9409

How do I toggle a SwiftUI toggle when a view is tapped?

I would like to toggle a Toggle when a view is tapped. Right now I have the following code and it works, though the Toggle doesn't animate the transition. What can I do to fix?

import SwiftUI

struct ContentView: View {
    
    @State private var toggle = false
    
    var body: some View {
        VStack {
            Toggle(isOn: $toggle) {
                Text("Hello World")
            }
        }.onTapGesture {
            print("Tapped!")
            self.toggle.toggle()
        }
    }
}

I've also tried to wrap the self.toggle.toggle() line around a DispatchQueue.main.asynch, but that didn't change anything.

Upvotes: 1

Views: 935

Answers (1)

Asperi
Asperi

Reputation: 257493

Make it with animation as below

}
// .contentShape(Rectangle())    // << add to make full-area tappable
.onTapGesture {
    print("Tapped!")
    withAnimation {
        self.toggle.toggle()
    }
}

Upvotes: 1

Related Questions