@State更改时,SwiftUI视图未更新

时间:2020-04-30 13:46:27

标签: swift swiftui state

使用@State时,我真的很难获得一个简单的SwiftUI文本视图进行更新。下面的代码。任何帮助表示赞赏(我敢肯定这很愚蠢,但我是所有新手-甚至无法正确复制/粘贴代码段)。谢谢。

struct ContentView : View {

    @State var tappedToggle: Bool = false

    var body: some View {
        Text("First: \(printRandomFactoid())").multilineTextAlignment(.center)
        .onTapGesture {
            self.tappedToggle.toggle()
            Text("Latest... \r \(printRandomFactoid())").multilineTextAlignment(.center)
        }
    }
}

1 个答案:

答案 0 :(得分:2)

视图永远不应该在动作关闭之内...意图可能是

struct ContentView : View {

    @State var tappedToggle: Bool = false

    var body: some View {
        Text(tappedToggle ? "First: \(printRandomFactoid())" : "Latest... \r \(printRandomFactoid())")
           .multilineTextAlignment(.center)
           .onTapGesture {
              self.tappedToggle.toggle()
        }
    }
}