我在 SwiftUI 中有一个垂直的 ScrollView。我正在努力让它快点。水平对齐效果很好,但垂直对齐则不行。我在模拟器和设备上检查了这一点。
struct ContentView: View {
@State private var scrolledID: Int?
@State private var items: [Int] = Array(0..<30)
var body: some View {
NavigationStack {
VStack {
if let scrolledID = scrolledID {
Text("scrolledID: \(scrolledID)")
} else {
Text("scrolledID: none")
}
Text("count: \(items.count)")
ScrollView(.vertical, showsIndicators: true) {
LazyVStack {
ForEach(items, id: \.self) { i in
RoundedRectangle(cornerRadius: 20)
.fill(Color.green)
.overlay {
Text("Item \(i)")
}
.foregroundStyle(.white)
.containerRelativeFrame(.vertical,
count: 5,
span: 2,
spacing: 10,
alignment: .center)
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned) // .paging
.safeAreaPadding([.vertical, .horizontal], 10)
.scrollPosition(id: $scrolledID, anchor: .bottom)
.toolbar {
Button("Scroll to first") {
scrolledID = items.first
}
}
}
}
}
}
将
.scrollTargetBehavior(.viewAligned)
替换为 .scrollTargetBehavior(.viewAligned(limitBehavior: .always))
后,顶部捕捉即可工作