A Abhishek
A Abhishek

Reputation: 77

Difference between toggle() and Toggle

I am learning Modals in SwiftUI and the code is below:

ContentView.swift:

import SwiftUI

struct ContentView: View {
    @State private var showingAddUser = false
    var body: some View {
      return  VStack {
        Text("Modal View")

        }.onTapGesture {
            self.showingAddUser.toggle()
            print(self.showingAddUser) //for console
        }

        .sheet(isPresented: $showingAddUser) {
            Addview(isPresented: self.$showingAddUser)
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

AddView.swift:

import SwiftUI

    struct Addview: View {
        @Binding var isPresented: Bool
        var body: some View {
            Button("Dismiss") {
                       self.isPresented = false
                   }
        }
    }

    struct Addview_Previews: PreviewProvider {
        static var previews: some View {
            Addview(isPresented: .constant(false))
        }
    }

When I try to run the code for the first time and check the print output in console, boolean value changes to true however if I initialise @State variable showingAddUser with true the console output is unchanged that is it remains true. Should't toggle() flip the boolean value to false?

Is this toggle() different from Toggle switch from a concept point of view?

Upvotes: 0

Views: 265

Answers (2)

Dc7
Dc7

Reputation: 1581

There is no need for isPresented Boolean in Add View

Try This

ContentView.swift

import SwiftUI

struct ContentView: View {
       @State private var showingAddUser = false
       var body: some View {
       return  VStack {
               Text("Modal View")

       }.onTapGesture {
              self.showingAddUser = true
              print(self.showingAddUser) //for console
       }

       .sheet(isPresented: $showingAddUser) {
             Addview()
       }
    }
 }

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

AddView.swift

import SwiftUI
struct AddView: View {

    var body: some View {
        Button(action:
             // Do Your Things
        ) {
            Text("MyButton")
        }
    }
}

struct Addview_Previews: PreviewProvider {
    static var previews: some View {
        Addview()
    }

Upvotes: 0

Frankenstein
Frankenstein

Reputation: 16341

The toggle() is a mutating function on value type Bool. If you set the initial value of showingAddUser as true it will display the AddUser View when launched initially and it's not if set to false, that's the difference.

Toggle is a SwiftUI View. It can be used as any other View in SwiftUI body, like this:

struct ContentView: View {
    @State var bool: Bool
    var body: some View {
        Toggle(isOn: $bool) {
            Text("Hello world!")
        }
    }
}

Upvotes: 2

Related Questions