gpt4 book ai didi

ios - 为什么 SwiftUI 的 ForEach 循环范围没有更新?

转载 作者:行者123 更新时间:2023-12-01 15:33:31 27 4
gpt4 key购买 nike

我试图在 ListView 内的 subview ( ContainerView )中显示项目列表每当这些项目的数组的值不是 nil 时.每次更新数组时都会有一个新的 ListView如果数组是 nil,应该显示替换前一个或删除.问题是ListView除了 ForEach 外,似乎已正确显示、删除和更新环形。它每次使用相同的范围,即使是新的 ListView似乎显示。

我创建了一个简单的例子来演示这个问题。这是ContainerView :

struct ContainerView: View {

@State private var items: [Int]?
private var listView: some View {
items.map { ListView(items: $0) }
}

var body: some View {
VStack {
Button("Display new List") { self.items = self.randomItems() }
listView
}
}

private func randomItems() -> [Int] {...}
}

这是 ListView :
struct ListView: View {

private let randomInt: Int
private let items: [Int]

init(randomInt: Int = Int.random(in: 100 ..< 999), items: [Int]) {
self.randomInt = randomInt
self.items = items
print("init | items: \(items)")
}

var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text("\(randomInt)")
ForEach(0 ..< items.count) { index -> Text? in
print("ForEach | index: \(index) items.count: \(self.items.count)")
return self.items.count > index ? Text("\(self.items[index])") : nil
}
}
}
}

运行此程序并多次点击“显示新列表”按钮时,它将打印如下内容:
init | items: [0, 1, 2]
ForEach | index: 0 items.count: 3
ForEach | index: 1 items.count: 3
ForEach | index: 2 items.count: 3
init | items: [0, 1, 2, 3, 4, 5, 6, 7, 8]
ForEach | index: 0 items.count: 9
ForEach | index: 1 items.count: 9
ForEach | index: 2 items.count: 9
init | items: [0, 1, 2, 3, 4, 5]
ForEach | index: 0 items.count: 6
ForEach | index: 1 items.count: 6
ForEach | index: 2 items.count: 6

所以显然是一个新的 ListView已创建,并且在设备上您还会看到正确的 randomInt显示,但由于某种原因 ForEach无论新数组有多长,每次都使用相同的范围。

为什么范围没有更新或者我如何强制它更新?

最佳答案

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
extension ForEach where Data == Range<Int>, ID == Int, Content : View {

/// Creates an instance that computes views on demand over a *constant*
/// range.
///
/// This instance only reads the initial value of `data` and so it does not
/// need to identify views across updates.
///
/// To compute views on demand over a dynamic range use
/// `ForEach(_:id:content:)`.
public init(_ data: Range<Int>, @ViewBuilder content: @escaping (Int) -> Content)
}

To compute views on demand over a dynamic range use ForEach(_:id:content:)

关于ios - 为什么 SwiftUI 的 ForEach 循环范围没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60754383/

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