Hi! I want to allow user to scroll a long list of items iOS app, so I am trying to embbed a List view in ScrollView view. However, the preview result doesn't work. Can you help me to check what I am missing?
Below is my experimental code I entered to the file ContentView.swift, started with Single Page App project.
struct ContentView: View {
var body: some View {
ScrollView{
List{
Text("abc")
Text("def")
}
.border(Color.yellow, width: 3)
.background(Color.blue)
}.padding(10).border(Color.red, width: 3)
}
}
The preview of this code shows the red borders of the ScrollView, but not showing anything for the list, nor the text inside. If I change "List" to "VStack", then everything worked as expected.
I don't understand why List doesn't work, and don't know how to fix it. Can you help me to find some clue?
Thank you!
List should already scroll—it's equivalent to UITableView. Simply remove the ScrollView and your application should work. For instance this will almost match what you've described above:
List {
Text("abc")
Text("def")
}
.border(Color.yellow, width: 3)
.background(Color.blue)
.padding(10)
.border(Color.red, width: 3)
Now, if your aim is to have the red border and the padding remain on screen while the list and its yellow border are scrolling, then you may have to do things a little differently. In this case, you can switch out the List with a ForEach to iterate over a collection, manually using a VStack to place a Divider view beneath each cell:
ScrollView {
ForEach(names, id: \.self) { name in
VStack {
Text(name)
Divider()
}
}
.border(Color.yellow, width: 3)
.background(Color.blue)
}
.padding(10)
.border(Color.red, width: 3)
Note that only a List will provide the appearance of 'empty' cells to fill up the screen.