ios - 为什么我在 SwiftUI 中更改发布的数组后,他没有更改?

标签 ios swift swiftui

所以,这只是我项目中的示例代码。调用 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/

相关文章:

ios - 检查数组值是否等于字符串

ios - 在 Swift 中创建 PDF

ios - 在 Swift 中将两个参数传递给 NSTimer

swift - NSViewController 中的 NSButton 对象不起作用

swiftui - 缩小选择器以适应内容而不是更大

ios - 修改 MFMessageComposeViewController UI 并以编程方式发送 SMS?

ios - 指定用户数据的有效方法

ios - 在 Swift 中更新变量之前数组正在更新

objective-c - 快速实现 Objective-C 设置图像舞会 Facebook 登录

pdf - Xcode 11 PDF 图像资源 "Preserve Vector Data"无法在 SwiftUI 中工作?