所以,这只是我项目中的示例代码。调用 SecondView 后,我想将数组中的名称更改为“LoL”,并显示它们。为什么 init() 不改变我的数组?因为它不显示新名称
struct Person: Identifiable {
let id = UUID()
var name: String
var index: Int
}
class User: ObservableObject {
@Published var array = [Person(name: "Nick", index: 0),
Person(name: "John", index: 1)
]
}
struct ContentView: View {
@ObservedObject var user = User()
var body: some View {
VStack {
ForEach (user.array) { row in
SecondView(name: row.name, index: row.index)
}
}
}
}
struct SecondView: View {
@ObservedObject var user = User()
var name = ""
var index = 0
init() {
user.array[index].name = "LoL"
}
init(name: String, index: Int) {
self.name = name
self.index = index
}
var body: some View {
VStack {
Text(name)
}
}
}
最佳答案
这是因为您没有在SecondView
中调用init()
方法,而是调用了init(name:, index:)
。请注意如何在 FirstView
的迭代(即 ForEach
)循环中使用 SecondView
初始值设定项。
此外,您的第二个 View 还显示沿初始值设定项 init(name:index:)
传递的名称,而不是 user
数组中的名称。因此,如果您想将 name
更改为某些内容,请在调用 init(name:index:)
之前执行此操作,并从用户数组传递名称。
您可以在第一个 View 中执行此操作。
struct ContentView: View {
@ObservedObject var user = User()
init() {
user.array[0].name = "LoL"
}
var body: some View {
VStack {
ForEach (user.array) { row in
SecondView(name: row.name, index: row.index)
}
}
}
}
请注意,它现在会将第一个名称更改为 Lol
,因为我们在 ContentView
的初始化程序中更改了它,然后该初始化程序使用相同的修改后的名称。
关于ios - 为什么我在 SwiftUI 中更改发布的数组后,他没有更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023313/