作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
是否可以在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/
我是一名优秀的程序员,十分优秀!