我正在尝试重现 Macos 苹果日历,但在进行水平无限滚动时遇到问题。日历需要始终显示 7 天,这意味着用户无法在任何位置滚动
这是我当前的代码,我在每天单元格的开头放置了一个矩形,如下所示: 我已经有一个带有每天单元格 ID 的 ScrollViewReader,但我无法让它在每天单元格开始时停止。
@State private var loadedDays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun","Mon1", "Tue1", "Wed1", "Thu1", "Fri1", "Sat1", "Sun1"]
@State private var scrollPos: String?
var body: some View {
GeometryReader { geomtry in
Text("\(scrollPos ?? "nil")")
ScrollViewReader { proxy in
ScrollView (.horizontal) {
LazyHStack(spacing: 10) {
ForEach($loadedDays, id: \.self) { day in
HStack {
Rectangle()
.frame(width: 5, height: 5, alignment: .leading)
.id("r" + day.wrappedValue)
VStack {
Text(day.wrappedValue)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
.id(day.wrappedValue)
Rectangle()
.frame(width: 5, height: 5, alignment: .trailing)
.id("l" + day.wrappedValue)
}.border().frame(width: geomtry.size.width/7)
}
}
.padding()
.scrollTargetLayout()
}
.defaultScrollAnchor(.center)
.onChange(of: scrollPos) { old, new in
if(new != nil && !new!.starts(with: "r")) {
withAnimation {
proxy.scrollTo("r" + new!, anchor: .leading)
}
}
}
}
.scrollPosition(id: $scrollPos)
}
}
使用此代码有时可以工作,但没有动画,但大多数时候它可以让我滚动到任何地方。
来自Sweeper的评论。我使用 scrollTargetBehavior(.viewAligned) 来解决问题
GeometryReader { geometry in
ScrollViewReader { proxy in
ScrollView (.horizontal) {
LazyHStack(spacing: 0) {
ForEach($loadedDays, id: \.self) { day in
HStack {
Rectangle()
.frame(width: 5, height: 5, alignment: .leading)
VStack {
Text(day.wrappedValue)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
Rectangle()
.frame(width: 5, height: 5, alignment: .trailing)
}
.border()
.frame(width: geometry.size.width/7)
}
}
.scrollTargetLayout()
}
//.defaultScrollAnchor(.center)
.scrollTargetBehavior(.viewAligned)
.defaultScrollAnchor(.leading)
}