Search code examples
swiftswiftuiviewbooleanconditional-statements

Change boolean value inside swiftui view


I have boolean variable (isTapped), once the app is launched, I'am giving it a true value, once it moves to (signupView) the app should test the value inside if statement to show some text and after that the app should change the value of (isTapped) to false!!

But it is not working!! as Type () cannot confirm to view. I tried to create a function and call it inside a view but it is not working either! Here is my code:

import SwiftUI

struct SignupView: View {
@AppStorage("isTapped") var isTapped : Bool?
var body: some View {
    if (isTapped == true){
        Text ("signup")
        isTapped = false 
        
    }
    else {
        Text ("Splash")
    }

}
}

Solution

  • If you want Text("signup") should be shown when isTapped is True, you need additional variable to keep the origin value

    struct SignupView: View {
        @AppStorage("isTapped") var isTapped : Bool = false
        @State var isTappedOrigin: Bool = false
        
        var body: some View {
            Group {
                if (isTappedOrigin == true){
                    Text ("signup")
                } else {
                    Text ("Splash")
                }
            }.onAppear {
                isTappedOrigin = isTapped
                isTapped = false
            }
        }
    }
    

    You need to set isTapped = true somewhere to see Text("signup") like this

    struct ContainView: View {
        @AppStorage("isTapped") var isTapped : Bool = false
        @State var show: Bool = false
        var body: some View {
            List {
                Toggle("isTapped", isOn: $isTapped)
                Button("show signup view") {
                    show.toggle()
                }
            }
            .sheet(isPresented: $show) {
                SignupView()
            }
        }
    }
    

    If you want to show signup only once when launch app it should be like this

    struct TestView: View {
        @AppStorage("isSignedUp") var isSignedUp : Bool = false
        @State var shouldShowSignUp : Bool = false
        
        var body: some View {
            Group {
                if shouldShowSignUp {
                    Text("Sign Up")
                } else {
                    Text("Splash")
                }
            }.onAppear {
                shouldShowSignUp = !isSignedUp
                isSignedUp = true
            }
        }
    }