I have a horizontal scroll view and a fixed array. I would like to loop it such that when I scroll left and get near the end, the array will add the items in the beginning to the end so that the user can continue to scroll. I would like this to happen when scrolling both left and right and to not have the current position of the user jump around. Here is my code. What am I missing? Would appreciate any and all help.
import SwiftUI
import Algorithms
struct ContentView: View {
@State private var timePosition = ScrollPosition(idType: Int.self, edge: .leading)
@State private var times: [Int] = Array(0...23)
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
LazyHStack(spacing: 0) {
ForEach(times, id:\.self) { time in
Text("\(time)")
.font(.system(.callout, design: .monospaced, weight: .semibold))
.padding(8)
.frame(width: 180, height: 110, alignment: .topLeading)
.border(width: 1, edges: [.leading, .trailing], color: .primary.opacity(0.05))
.id(time)
}
}
.scrollTargetLayout()
}
.frame(height: 110)
.scrollPosition($timeScrollPosition, anchor: .center)
.onScrollTargetVisibilityChange(idType: Int.self) { timeIDs in
if let currentViewID = model.timeScrollPosition.viewID {
if timeIDs.contains(times[times.count - 2]) {
times.rotate(toStartAt: times.count - 1)
}
if timeIDs.contains(times[1]) {
times.rotate(toStartAt: times.count-1)
}
print("New times: \(times)")
timeScrollPosition.scrollTo(id: currentViewID)
}
}
}
}