2

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)
            }
        }
    }
}
3
  • Unrelated but ForEach(times, id:\.self) needs to be changed to ForEach(0..<24) to prevent a crash because of invalid id key path. Commented Jun 25, 2024 at 6:59
  • 1
    There are a number of similar post/answers on SO and examples on the net, search using the word carousel. For example: stackoverflow.com/questions/72343827/carousel-view-swiftui and stackoverflow.com/questions/76824297/… Commented Jun 25, 2024 at 7:06
  • 1
    @workingdogsupportUkraine none of those achieve what i want Commented Jul 2, 2024 at 22:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.