问题描述
在 Scrollview 内部,我使用带有固定标题的 Lazyvstack,并根据滚动位置操纵该标题的比例。
在 Lazyvstack 中,我有一个 ForEach 迭代一些项目列表。但是,如果我使用嵌套的 ForEach 循环(例如,将项目按月分组),滚动视图会变得非常有问题/跳跃。
最小可重复代码:
struct nested: View {
@State var yValueAtMinScale: Double = 100 // y value at which header is at minimum scale (used for linear interpolation)
@State var headerScale = 1.0
var restingScrollYValue = 240.0 // y value of scroll notifier when scrollview is at top
var body: some View {
ZStack {
ScrollView {
Lazyvstack(pinnedViews: [.sectionHeaders]) {
Section(
header:
Circle()
.fill(Color.red)
.frame(width: 150,height: 150)
.scaleEffect(CGFloat(headerScale),anchor: .top)
.zIndex(-1)
) {
// scroll position notifier
// i set the header's scale based on this view's global y-coordinate
GeometryReader { geo -> AnyView in
let frame = geo.frame(in: .global)
print("miny",frame.minY)
dispatchQueue.main.async {
self.headerScale = calculateHeaderScale(frameY: frame.minY)
}
return AnyView(Rectangle()) // hack
}
.frame(height: 0) // zero height hack
ForEach(1...10,id: \.self) { j in
Section {
Text("\(j)")
// works without nested loop
ForEach(1...3,id: \.self) { i in
Rectangle()
.frame(height: 50)
.padding(.horizontal)
.id(UUID())
}
}
}
}
}
}
}
}
// interpolates some linear value bounded between 0.75 and 1.5x,based on the scroll value
func calculateHeaderScale(frameY: CGFloat) -> Double {
let minScale = 0.75
let linearValue = (1-minScale) * (Double(frameY) - yValueAtMinScale) / (restingScrollYValue - yValueAtMinScale) + minScale
return max( 0.75,min(1.5,linearValue) )
}
}
删除内部嵌套的 ForEach 循环可以解决问题。这里会发生什么?我认为在每次滚动更新时更新标题比例会导致视图更新过多并导致故障,但这并不能解释为什么它适用于一个 ForEach 循环。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)