struct LandmarkList: View {
var body: some View {
NavigationView {
List(landmarkData) { landmark in
LandmarkRow(landmark: landmark)
}
}
}
}
I want to display a message at the centre of the view when the list view (table view) is empty. What is the best way to achieve this in SwiftUI. Is checking for the data source count in "onAppear" and setting some sort of Bool value the correct approach ?
struct LandmarkList: View {
var body: some View {
NavigationView {
if landmarkData.count == 0 {
VStack {
Text("is empty")
} else {
List(landmarkData) { landmark in
LandmarkRow(landmark: landmark)
}
}
}
}
}
I would simply try an if else statement. If landmarkdata is nil or count = 0, show a text. Else show the list.
If you want your message to have the same behavior as a list item, use ScrollView
and GeometryReader
.
Embed the condition state in the Group
, so that the NavigationView
is displayed in any case.
Don't forget to change the background color and ignore the safe area, for more resemblance to a list.
struct LandmarkList: View {
var body: some View {
NavigationView {
Group {
if landmarkData.isEmpty {
GeometryReader { geometry in
ScrollView {
Text("Your message!")
.multilineTextAlignment(.center)
.padding()
.position(x: geometry.size.width/2, y: geometry.size.height/2)
}
}
.background(Color(UIColor.systemGroupedBackground))
} else {
List(landmarkData) { landmark in
LandmarkRow(landmark: landmark)
}
}
}
.ignoresSafeArea()
.navigationTitle("Title")
}
}
}
You can also use @ViewBuilder
to provide an empty state view in the list, as suggested in this answer .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.