I want to show a flag in the main view if the user selected that country 2 views before getting to the main view.
The code for the page where the user selects the country is:
struct ChooseLanguageWithButtonView: View {
@State var isSelected1 = false
@State var isSelected2 = false
var body: some View {
ZStack {
Color.white
.edgesIgnoringSafeArea(.all)
VStack {
ScrollView (showsIndicators: false) {
VStack(spacing: 20){
VStack(alignment: .leading){
Text("Choose the language you want to learn!")
.font(.custom("Poppins-Bold", size: 25))
Text("Select one language")
.opacity(0.5)
.font(.custom("Poppins-Light", size: 15))
.frame(alignment: .bottomTrailing)
.padding(5)
Spacer()
}
.padding(.top, -25)
HStack (spacing: 30){
ButtonLanguage(
isSelected: $isSelected1,
color: .orangeGradient1,
textTitle: "English",
textSubtitle: "American",
imageLang: "englishAmerican",
imageFlag: "1"
)
.onTapGesture(perform: {
isSelected1.toggle()
if isSelected1 {
isSelected2 = false
}
})
ButtonLanguage(
isSelected: $isSelected2,
color: .orangeGradient1,
textTitle: "English",
textSubtitle: "British",
imageLang: "telephone",
imageFlag: "0"
)
.onTapGesture(perform: {
isSelected2.toggle()
if isSelected2 {
isSelected1 = false
}
})
}
NavigationLink(destination: {
if isSelected1 {
EnglishAmericanLevelView()
} else if isSelected2 {
EnglishBritishView()
}
}, label: {
Text("Let's Go")
.bold()
.foregroundColor(Color.white)
.frame(width: 200, height: 50)
.cornerRadius(40)
})
On the main view if the user chose english american I want to show the american flag.
Someone can help me with that please?
2
Answers
It sounds like a global class might be good to use here, so you can set variables like this that later you can reference in your views.
In your main project app file you can initialize the class with the
.environmentObject
methodYou can then reference the global class in any view as follows
Then you can set the variable to be whatever you’d like and then use it in an if statement to show your image. For example . . .
Otherwise you will have to pass the show flag object from view to view
Assuming you are using MVVM pattern, then you can create a published Bool variable in the ViewModel and pass it in the environment.
Something passed in the environment can be accessed from all descendents of the view.
Pass the ViewModel it to either the MainView or ChildView as an environment object.
You can get a reference to the MainViewModel inside the ChildView from the
environment and use the
showAmericanFlag
variable.