[英]Getting content offset of List in SwiftUI
我正在尝试在 SwiftUI 中创建这样的视差标题效果https://twitter.com/KhaosT/status/1140814602017464320 ,但真的不知道如何在滚动时获取列表的内容偏移量。
有谁知道如何在滚动时计算列表的内容偏移量?
我在这个答案中为ScrollView
案例提供了一个可重用的解决方案,它利用视图首选项作为一种方法来通知视图层次结构中的上游布局信息。
有关“查看首选项”如何工作的详细说明,我建议您阅读kontiki 撰写的关于该主题的3 篇系列文章
不幸的是,这种解决方案不适用于List
(可能是一个错误),因为View Preferences被困在List
并且对其祖先不可见。
目前唯一可行的解决方案是观察列表内视图的帧变化。 您可以通过两种方式实现这一目标:
您可以报告和收听列表中每个视图(单元格)的布局更改(并对其进行操作):
struct TestView1: View {
var body: some View {
GeometryReader { geometry in
List(TestEnum.allCases) { listValue in
Text(listValue.id)
.padding(60)
.transformAnchorPreference(key: MyKey.self, value: .bounds) {
$0.append(MyFrame(id: listValue.id, frame: geometry[$1]))
}
.onPreferenceChange(MyKey.self) {
print($0)
// Handle content frame changes here
}
}
}
}
}
或者,如果您不需要每个单元格上的框架更改,则报告并侦听某些表标题视图(或空标题)上的框架更改:
struct TestView2: View {
var body: some View {
GeometryReader { geometry in
List {
Text("")
.transformAnchorPreference(key: MyKey.self, value: .bounds) {
$0.append(MyFrame(id: "tableTopCell", frame: geometry[$1]))
}
.onPreferenceChange(MyKey.self) {
print($0)
// Handle top view frame changes here.
// This only gets reported as long as this
// top view is part of the content. This could be
// removed when not visible by the List internals.
}
ForEach(TestEnum.allCases) {
Text($0.rawValue)
.padding(60)
}
}
}
}
}
在下面找到上述解决方案的支持代码:符合PreferenceKey
结构、可识别的视图框架结构和作为数据源的测试枚举:
struct MyFrame : Equatable {
let id : String
let frame : CGRect
static func == (lhs: MyFrame, rhs: MyFrame) -> Bool {
lhs.id == rhs.id && lhs.frame == rhs.frame
}
}
struct MyKey : PreferenceKey {
typealias Value = [MyFrame] // The list of view frame changes in a View tree.
static var defaultValue: [MyFrame] = []
/// When traversing the view tree, Swift UI will use this function to collect all view frame changes.
static func reduce(value: inout [MyFrame], nextValue: () -> [MyFrame]) {
value.append(contentsOf: nextValue())
}
}
enum TestEnum : String, CaseIterable, Identifiable {
case one, two, three, four, five, six, seven, eight, nine, ten
var id: String {
rawValue
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.