Search code examples
iosswiftswiftuiswiftui-listempty-list

How to display a text message at the Center of the view when the List datasource is empty in SwiftUI?


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 ?


Solution

  • struct LandmarkList: View {
        var body: some View {
            NavigationView {
                if landmarkData.count == 0 {
                  VStack {
                    Text("is empty")
                  } else {
                  List(landmarkData) { landmark in
                     LandmarkRow(landmark: landmark)
                  }
               }
            }
        }
    }