How to make a Horizontal List in SwiftUI?

Viewed 29764

I can wrap all my views inside a List

List {
   // contents
}

But this seems to be vertical scrolling. How do I make it horizontal?

4 Answers

You need to add .horizontal property to the scrollview. otherwise it won't scroll.

ScrollView (.horizontal, showsIndicators: false) {
     HStack {
         //contents
     }
}.frame(height: 100)

Starting from iOS 14 beta1 & XCode 12 beta1 you will be able to wrap LazyHStack in a ScrollView to create a horizontal lazy list of items, i.e., each item will only be loaded on demand:

ScrollView(.horizontal) {
            LazyHStack {
                ForEach(0...50, id: \.self) { index in
                    Text(String(index))
                        .onAppear {
                            print(index)
                        }
                }
            }
        }

To make a horizontal scrollable content, you can wrap a HStack inside a ScrollView:

ScrollView {
  HStack {
    ForEach(0..<10) { i in
      Text("Item \(i)")
      Divider()
    }
  }
}
.frame(height: 40)

You can use .horizontal property and use custom elements. For me I use cusomt CircleView

  var body: some View {
        VStack{
            Divider()
            ScrollView(.horizontal){
                HStack(spacing:10){
                    ForEach(0..<10){
                        index in
                        CircleView(label: "\(index)")
                    }
                }.padding()
            }.frame(height:100)
            Divider()
            Spacer()
        }
        
    }
}

    //struct CircleView:View
    @State var label:String
    var body:some View {
        ZStack{
            Circle()
                .fill(Color.yellow)
                .frame(width: 70, height: 70)
            Text(label)
        }
    }
}
Related