Reputation: 637
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.
I should use both of them.
.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
}
}
}
}
Anyone know why this happens and(or) how to fix?
Upvotes: 47
Views: 30496
Reputation: 1809
If you want a header, use a section.
var body: some View {
List {
Section {
ForEach(numbers, id: \.self) {
Text("\($0)")
}
.onDelete { index in
// delete item
}
} header: {
Text("Header").font(.title)
}
}
}
Upvotes: -1
Reputation: 654
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)
}
}
}
}
Upvotes: 33
Reputation: 1984
There is no need for two scrolling objects. 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
}
}
}
Upvotes: 22
Reputation: 257493
Just put header inside the List, like
var body: some View {
List {
Text("Header").font(.title)
ForEach(numbers, id: \.self) {
Text("\($0)")
}
.onDelete { index in
// delete item
}
}
}
Upvotes: 3