gpt4 book ai didi

swift - 如何在 swiftui 中强制 View 更新 onAppear

转载 作者:行者123 更新时间:2023-11-30 10:34:02 28 4
gpt4 key购买 nike

是否可以在Appear上查看内容 View ?该方法被调用,但列表未更新似乎应该有某种方法来做到这一点

import SwiftUI

var texts = ["0", "0", "0"]

struct ContentView: View {


var body: some View {
List {
Text(texts[0])
Text(texts[1])
Text(texts[2])

}
.onAppear(){
texts[0] = "1"
print(texts)
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

最佳答案

如果你想重新渲染,你需要使用状态。

如果将 texts 变量带入 ContentView 结构并将其声明为 @State 那么它将导致 ContentView 重新渲染。

请注意,当您在闭包中引用texts时,您必须在onAppear中使用self

struct ContentView: View {

@State private var texts = ["0", "0", "0"] . // Apple suggests that these should be private

var body: some View {
List {
Text(texts[0])
Text(texts[1])
Text(texts[2])

}
.onAppear(){
self.texts[0] = "1"
print(self.texts)
}
}
}
<小时/>

但是,如果您想在多个 View 之间共享文本,那么您将需要创建一个环境对象。您可以按如下方式执行此操作:

创建一个 ObservableObject。

class Texts: ObservableObject {
@Published var texts = ["0", "0", "0"] // You can obviously choose whichever name you want for this variable.
}

然后在您的 SceneDelegate 中创建该对象的实例并将其附加到您的 ContentView。

let texts = Texts()
let contentView = ContentView().environmentObject(texts)

然后在 ContentView.swift 中你可以像这样使用它:

struct ContentView: View {

@EnvironmentObject var texts: Texts

var body: some View {
List {
// notice that you have to access the texts array that is stored in texts object
Text(texts.texts[0])
Text(texts.texts[1])
Text(texts.texts[2])

}
.onAppear(){
self.texts.texts[0] = "1"
print(self.texts.texts)
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView().environmentObject(Texts())
}
}

关于swift - 如何在 swiftui 中强制 View 更新 onAppear,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58462716/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com