Reputation: 1349
I am trying to create a simple list view in SwiftUI however, it shows up as blank (pictured below) no matter how many objects are in the array. If I get rid of the list, it will show the elements of the array. I know for a fact that the array is not empty. Any recommendations on how to fix it.
This is my code"
var body: some View {
NavigationView {
ScrollView {
if(leaderboard.isEmpty) {
VStack {
Text("No Entries Yet :(")
.foregroundColor(.gray)
.font(.largeTitle)
}
} else {
ScrollView {
List {
ForEach(leaderboard.asArray(), id: \.self) { score in
Text("\(score)")
}
}
}
}
}
.navigationBarTitle("Leaderboard")
}
}
Here is what the view currently shows:
Also, bonus points if you can help me make it so the Text("No Entries Yet :( ")
is centered vertically within the view.
Upvotes: 0
Views: 1615
Reputation: 4994
If your list is empty, just add another row without background. Stylish it as you want.
if rows.isEmpty {
Text("No records")
.listRowBackground(EmptyView())
}
Upvotes: 0
Reputation: 115041
You don't need either of those ScrollView
s - If the list is empty you only have the text view. If the list isn't empty, List
provides the necessary scroll view.
To vertically centre the text when the list is empty, simply add Spacer
views above and below:
struct ContentView: View {
var body: some View {
let leaderboard:[Int] = [10,20,30,40,100,1999,1393,444]
NavigationView {
if(leaderboard.isEmpty) {
VStack {
Spacer()
Text("No Entries Yet :(")
.foregroundColor(.gray)
.font(.largeTitle)
Spacer()
}
} else {
List {
ForEach(leaderboard, id: \.self) { score in
Text("\(score)")
}
}
}
}
.navigationBarTitle("Leaderboard")
}
}
Upvotes: 1