【发布时间】:2021-11-19 02:50:06
【问题描述】:
我正在尝试使用.id(_:) 使用 ForEach 进行一些程序化滚动,这样每次使用 ForEach 将新部分添加到表单时都会滚动表单。但是,我遇到了一些不良行为,我想了解导致所述行为的机制。正如您在屏幕截图中看到的那样,第三个文本视图甚至没有出现。当我删除 id 方法时,所有三个 Text 视图都会按您的预期显示。
import SwiftUI
struct ContentView: View {
@State private var array: [Int] = [1]
var body: some View {
ScrollViewReader { p in
NavigationView {
Form {
ForEach(self.array, id: \.self) { num in
Section {
Text("Hello")
Text("My name is slim shady")
Text("number \(num)")
}
.id(num)
.onChange(of: array.count) { count in
p.scrollTo((count + 1), anchor: .top)
}
}
}
.toolbar {
ToolbarItem(placement: .bottomBar) {
Button("add") {
array.append(array.count + 1)
}
}
}
}
}
}
}
任何帮助将不胜感激!干杯。
【问题讨论】: