Home > other >  How to make infinite ScrollView with infinite amount of items in SwiftUI
How to make infinite ScrollView with infinite amount of items in SwiftUI

Time:05-26

I'm new to IOS and SwiftUI so please correct any incorrect assumptions I make.

I need to make a View in SwiftUI that has similar functionality to RecyclerView in android.

Specifically what I'm trying to make is a horizontal ScrollView where the displayed item (the one in the centre of the screen) is constructed by its index. for example If I'm looking at index 0 then it will display a card with some date text in ie (1st Jan 2022) then index 1 will display 2nd jan 2022, index 2 3rd jan 2022 ect...

So you can see it could theoretically go on forever if the user wants to scroll far enough. Because of this I can't create a list of objects and loop over them in a HStack. So I want some kind of functionality where I only create 3 cards and then when i scroll to the right and the index 0 card goes out of sight, it is reused as the 'new' card at the right (end) of the ScrollView. The same behaviour as the RecyclerView.

The most important thing is I need to be able to access the index for a particular rendered card, without that i can't construct my data.

CodePudding user response:

You can use LazyHGrid to achieve RecyclerView functionality

struct ContentView: View {
    // MARK: - PROPERTIES
    
    let gridItems = [
        GridItem(.flexible()),
        GridItem(.flexible())
    ]
    
    var body: some View{
        ScrollView(.horizontal, showsIndicators: false) {
            LazyHGrid(rows: gridItems, alignment: .center, spacing: 10) {
                ForEach(0...10, id: \.self){ number in
                    // You can create your own ReusableView and put it here
                    Text("\(number)")
                        .frame(width: 100)
                        .background(.blue)
                }
            }
        }
        .frame(height: 100)
    }

}

// MARK: - PREVIEW

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Preview

  • Related