4
votes
    struct Flashcard : View {
      @State var frontText = newArray[randomNum].kana
      @State var backText = newArray[randomNum].romaji

      var body: some View {
        let zstack = ZStack {
          Frontside(kanatext: frontText)
            .background(Color.yellow)
            .rotation3DEffect(.degrees(self.showResults ? 180.0 : 0.0), axis: (x: 0.0, y: 1.0, z: 0.0))
            .zIndex(self.showResults ? 0 : 1)
            .frame(width: 300, alignment: .center)
            .cornerRadius(25)
         }
      }

public struct Frontside: View
{
    @State public var kanatext: String = ""

    public var body: some View
    {
        Text(self.kanatext)
            .font(.title)
            .fontWeight(.black)
            .padding(32)
    }
}

In my code snippet above, when I update the @State var frontText, I'm expecting my view to refresh and display the frontText. But for some reason it won't show the new frontText when it is used in my Frontside struct. If I just print Text(frontText) in my view, it will always refresh as the variable changes. What am I missing for it to refresh properly whenever frontText is updated? Thanks.

1

1 Answers

3
votes

You have to declare kanatext as @Binding:

@Binding public var kanatext: String

and then pass the binding to your state, which is owned by the parent view in the initialiser:

Frontside(kanatext: $frontText)

Basically, when you declare a variable inside a view @State - you indicated that this view owns it and the way it is drawn is dependent on it. When you want this state to influence another view you need to pass it in as binding (the $). IF both reference the same variable as @State each has it's own independent copy as they are all value types.