Using a button that correlates to the for loop index is not in the right order at first (swiftui)

huangapple go评论73阅读模式
英文:

Using a button that correlates to the for loop index is not in the right order at first (swiftui)

问题

以下是您要翻译的代码部分:

我有一个通过名为'countries'的数组进行迭代的for循环,该数组包含约5-10个'Country'类型的结构体。数组的每次循环都会在HStack中创建一个按钮,按钮的操作将一个变量设置为所点击的国家(以传递给下一个视图)。

让我举个问题的示例场景: 假设for循环加载并且我点击了哥斯达黎加。理论上,countrySelected变量应该设置为哥斯达黎加,fullScreenCover应该为true。下一个视图加载后,显示的国家却是不正确的。如果我返回并选择相同的国家,它会做同样的事情。只有在我选择了不同的国家之后才开始工作。

不确定是什么原因导致了这个问题。我知道我可以使用导航链接来解决这个问题,但在我的情况下我不能使用它。任何帮助都将不胜感激!

以下是showingCountryPage,如果为true,则激活fullScreenCover,countrySelected跟踪在for循环中单击的国家按钮

@State private var showingCountryPage = false
@State var countrySelected = Country(name: "Brazil", code: "BR", continent: "South America")

以下是国家数组的示例

@State var countries = [Country(name: "France", code: "FR", continent: "Europe"), Country(name: "United States", code: "US", continent: "North America")].shuffled()

以下是视图内部for循环的代码

ScrollView(.horizontal, showsIndicators: false) {
    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)
英文:

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)

</details>


# 答案1
**得分**: 1

尝试使用`.fullScreenCover(item: ...)`这种方式:

```swift
@State var countrySelected: Country?
// ....

.fullScreenCover(item: $countrySelected) { country in
    NavigationView {
        ViewCountryHome(country: country)
    }
}

不需要使用showingCountryPage

英文:

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.

huangapple
  • 本文由 发表于 2023年5月17日 07:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76267660.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定