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")
}
}
}
CodePudding user response:
You can't set anything to a variable inside the view hierarchy. So to achieve what you want to do, maybe you could try this:
var body: some View {
if (isTapped == true){
Text ("signup")
.onAppear {
isTapped = false
}
} else {
Text ("Splash")
}
}
onAppear
closure is run outside the view hierarchy, so you can set values to a variable.
**Update: Re: your comment, that's how SwiftUI works. When isTapped = false
is set in onAppear
, SwiftUI immediately reloads the body and the splash will be shown. I think to achieve what you need, you shouldn't use @AppStorage
. It will cause an update of the body when it's updated. Why don't you just use UserDefaults
like this?:
let isTapped: Bool? = UserDefaults.standard.bool(forKey: "isTapped")
...
Text ("signup")
.onAppear {
UserDefaults.standard.set(false, forKey: "username")
}
CodePudding user response:
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
}
}
}