为什么我的函数在使用@State 时不更新文本?

Why is my function not updating the text while using @State?

对于我的高级顶点,我基本上尝试自学 SwiftUI 并创建一个我想到的文字游戏应用程序。到目前为止,我遇到了很多问题,但我一直坚持不懈,但这个问题真的让我感到不安。我试图在按下按钮时更新文本。我真的不知道如何解决这个问题,因为我是 SwiftUI 的新手。有谁知道有什么可以帮助的吗?如果能得到任何帮助,我将不胜感激。这是我为此使用的代码:

struct descriptions { 
  @State var page: Int = 0 
  func switchDesc() -> String { 
      switch page { 
         case 0: 
            return [game text] 
         case 1: 
            return [game text] 
         case 2: 
            return [game text] 
         default: 
            return "" 
    } 
  } 
}

struct GameView: View { 
    // [other variables]
    @Binding var page: Int 
    @State var desc: String = descriptions().switchDesc()
    var body: some View { 
        [...] 
        HStack { 
            Button(
                action: { 
                    page -= 1 
                    desc = descriptions().switchDesc() 
                }, 
                label: { 
                    Image(systemName: "arrowtriangle.left.circle.fill") 
                }
            )
           Spacer()
           Button(
            action: {
                page += 1
                desc = descriptions().switchDesc() 
            },
            label: {
                Image(systemName: "arrowtriangle.right.circle.fill")}
            )
         }
    }
}

@State 变量需要在 View 中才能像您期望的那样运行。此外,您不需要单独的 @State 变量来描述。相反,您可以仅更新 page,然后根据当前的 page.

让您的 switchDesc return 获得正确的值

例如:


struct GameView: View {
    @State var page: Int = 0
    
    func switchDesc() -> String {
        switch page {
        case 0:
            return "Text1"
        case 1:
            return "Text2"
        case 2:
            return "Text3"
        default:
            return ""
        }
    }
    
    var body: some View {
        Text(switchDesc())
        HStack {
            Button(action: {
                page -= 1
            }) {
                Image(systemName:"arrowtriangle.left.circle.fill")
            }
            Spacer()
            Button(action: {
                page += 1
            }) {
                Image(systemName: "arrowtriangle.right.circle.fill")
            }
        }
    }
}

在您的原始代码中,您将 page 作为 @Binding -- 您将我的示例更改为相同的东西。我刚刚做到了 @State 因为现在(没有看到任何其他代码),它似乎将归此视图所有。无论哪种方式,描述都会根据 page 变量的状态正确更新。


根据评论更新:

struct ContentView : View {
    @State var page = 0
    
    var body: some View {
        GameView(page: $page)
    }
}

struct GameView: View {
    @Binding var page: Int
    //etc