Reputation: 376
I have a for loop that iterates through an array called 'countries' that contains about 5-10 structs of the type 'Country'. Each loop of the array creates a button in an HStack and the button action sets a variable equal to country that was clicked (to pass to the next view)
Let me give an example scenario of the issue: Let's say the for loop loads and I click on Costa Rica. Hypothetically the countrySelected variable should be set to Costa Rica and the fullScreenCover should be true. The next view loads and the incorrect country is shown. If i go back and select the same country it does the same thing. It only starts to work after I select a different country.
Not sure what is causing this issue. I know I could use a Navigation Link to make it work but in my case I can't use it. Any help is appreciated!
Below is showingCountryPage which if true will activate the fullScreenCover and countrySelected which keeps track of which country button was click in the for loop
@State private var showingCountryPage = false
@State var countrySelected = Country(name: "Brazil", code: "BR", continent: "South America")
Below is an example of the countries array
@State var countries = [Country(name: "France", code: "FR", continent: "Europe"), Country(name: "United States", code: "US", continent: "North America")].shuffled()
Below is the code for the for loop inside the view
HStack(spacing: 12){
Text(" ")
ForEach(countries, id: \.self){country in
Button(action: {
self.countrySelected = country
showingCountryPage = true
}){
ZStack(alignment: .center){
ZStack{
Image(country.code.lowercased() + "1")
.resizable()
.scaledToFill()
.frame(width: 200, height: 150)
.clipped()
Color.white
.opacity(0)
.frame(width: 200, height: 150)
.background(
LinearGradient(gradient: Gradient(colors: [.clear, .black, .clear]), startPoint: .top, endPoint: .bottom).opacity(0.4))
}
Text(country.name)
.font(.custom(
"Poppins-SemiBold",
fixedSize: 18))
.foregroundColor(.white)
.padding()
.multilineTextAlignment(.center)
.shadow(color: .black.opacity(0.25), radius: 1, x: 0, y: 0)
}.frame(width: 200, height: 150).cornerRadius(10).padding(.vertical)
}.fullScreenCover(isPresented: $showingCountryPage, content: {NavigationView{ViewCountryHome(country: countrySelected)}})
}
}
}.padding(.top, 5)
Upvotes: 0
Views: 42
Reputation: 36782
try this approach using .fullScreenCover(item:...)
such as:
@State var countrySelected: Country?
// ....
.fullScreenCover(item: $countrySelected) { country in
NavigationView {
ViewCountryHome(country: country)
}
}
No need for showingCountryPage
.
Upvotes: 1