Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI List inside ScrollVIew

I want to make my List inside a ScrollView so that I can scroll List rows and headers together. But I found that List inside ScrollView isn't working. It shows nothing. Anyone know why this happens and(or) how to fix?

I should use both of them.

  • I should use ScrollView so that I can make my header(image or text) also scrolled when I scroll the rows.
  • I should use List to use .ondelete() method.

my sample code is below.

@State private var numbers = [1,2,3,4,5,6,7,8,9]

var body: some View {
    ScrollView {
        Text("header")
        List {
            ForEach(numbers, id: \.self) {
                Text("\($0)")
            }
            .onDelete { index in
                // delete item
            }
        }
    }
}
like image 774
Jex Jang Avatar asked Mar 15 '20 01:03

Jex Jang


2 Answers

It is possible but not when the List is using the full screen.

In the code example I used GeometryReader to make the list as big as possible. But you can also remove the GeometryReader and just insert a fixed dimension into .frame()

 struct ContentView: View {
    
    @State private var numbers = [1,2,3,4,5,6,7,8,9]
    
    var body: some View {
        GeometryReader { g in
            ScrollView {
                Text("header")
                List {
                    ForEach(self.numbers, id: \.self) {
                        Text("\($0)")
                    }
                    .onDelete { index in
                        // delete item
                    }
                }.frame(width: g.size.width - 5, height: g.size.height - 50, alignment: .center)
            }
        }
    }
}

enter image description here

like image 65
Volker88 Avatar answered Sep 20 '22 10:09

Volker88


There is no need of Two scrolling object you can also use section for this

    @State private var numbers = [1,2,3,4,5,6,7,8,9]

    var body: some View {
        List {
            Section.init {
                Text("Header")
            }
            ForEach(numbers, id: \.self) {
                Text("\($0)")
            }
            .onDelete { index in
                // delete item
            }
        }
    }
like image 42
Anil Kumar Avatar answered Sep 22 '22 10:09

Anil Kumar