SwiftUI list empty state view/modifier

Viewed 5581

I was wondering how to provide an empty state view in a list when the data source of the list is empty. Below is an example, where I have to wrap it in an if/else statement. Is there a better alternative for this, or is there a way to create a modifier on a List that'll make this possible i.e. List.emptyView(Text("No data available...")).

import SwiftUI

struct EmptyListExample: View {

    var objects: [Int]

    var body: some View {
        VStack {
            if objects.isEmpty {
                Text("Oops, loos like there's no data...")
            } else {
                List(objects, id: \.self) { obj in
                    Text("\(obj)")
                }
            }
        }
    }

}

struct EmptyListExample_Previews: PreviewProvider {

    static var previews: some View {
        EmptyListExample(objects: [])
    }

}
6 Answers

One of the solutions is to use a @ViewBuilder:

struct EmptyListExample: View {
    var objects: [Int]

    var body: some View {
        listView
    }

    @ViewBuilder
    var listView: some View {
        if objects.isEmpty {
            emptyListView
        } else {
            objectsListView
        }
    }

    var emptyListView: some View {
        Text("Oops, loos like there's no data...")
    }

    var objectsListView: some View {
        List(objects, id: \.self) { obj in
            Text("\(obj)")
        }
    }
}

I quite like to use an overlay attached to the List for this because it's quite a simple, flexible modifier:

struct EmptyListExample: View {

    var objects: [Int]

    var body: some View {
        VStack {
            List(objects, id: \.self) { obj in
                Text("\(obj)")
            }
            .overlay(Group {
                if objects.isEmpty {
                    Text("Oops, loos like there's no data...")
                }
            })
        }
    }
}

It has the advantage of being nicely centred & if you use larger placeholders with an image, etc. they will fill the same area as the list.

You can create a custom modifier that substitutes a placeholder view when your list is empty. Use it like this:

List(items) { item in
    Text(item.name)
}
.emptyPlaceholder(items) {
    Image(systemName: "nosign")
}

This is the modifier:

struct EmptyPlaceholderModifier<Items: Collection>: ViewModifier {
    let items: Items
    let placeholder: AnyView

    @ViewBuilder func body(content: Content) -> some View {
        if !items.isEmpty {
            content
        } else {
            placeholder
        }
    }
}

extension View {
    func emptyPlaceholder<Items: Collection, PlaceholderView: View>(_ items: Items, _ placeholder: @escaping () -> PlaceholderView) -> some View {
        modifier(EmptyPlaceholderModifier(items: items, placeholder: AnyView(placeholder())))
    }
}

I tried @pawello2222's approach, but the view didn't get rerendered if the passed objects' content change from empty(0) to not empty(>0), or vice versa, but it worked if the objects' content was always not empty.

Below is my approach to work all the time:

struct SampleList: View {

    var objects: [IdentifiableObject]

    var body: some View {
    
        ZStack {
        
            Empty() // Show when empty
        
            List {
                ForEach(objects) { object in
                    // Do something about object
                }
            }
            .opacity(objects.isEmpty ? 0.0 : 1.0)
        }
    }  
}  

You can make ViewModifier like this for showing the empty view. Also, use View extension for easy use.

Here is the demo code,

//MARK: View Modifier
struct EmptyDataView: ViewModifier {
    let condition: Bool
    let message: String
    func body(content: Content) -> some View {
        valideView(content: content)
    }
    
    @ViewBuilder
    private func valideView(content: Content) -> some View {
        if condition {
            VStack{
                Spacer()
                Text(message)
                    .font(.title)
                    .foregroundColor(Color.gray)
                    .multilineTextAlignment(.center)
                Spacer()
            }
        } else {
            content
        }
    }
}

//MARK: View Extension
extension View {
    func onEmpty(for condition: Bool, with message: String) -> some View {
        self.modifier(EmptyDataView(condition: condition, message: message))
    }
}

Example (How to use)

struct EmptyListExample: View {
    
    @State var objects: [Int] = []
    
    var body: some View {
        NavigationView {
            List(objects, id: \.self) { obj in
                Text("\(obj)")
            }
            .onEmpty(for: objects.isEmpty, with: "Oops, loos like there's no data...") //<--- Here
            .toolbar {
                ToolbarItemGroup(placement: .navigationBarTrailing) {
                    Button("Add") {
                        objects = [1,2,3,4,5,6,7,8,9,10]
                    }
                    Button("Empty") {
                        objects = []
                    }
                }
            }
        }
    }
}

enter image description here

In 2021 Apple did not provide a List placeholder out of the box.

In my opinion, one of the best way to make a placeholder, it's creating a custom ViewModifier.

struct EmptyDataModifier<Placeholder: View>: ViewModifier {

    let items: [Any]
    let placeholder: Placeholder

    @ViewBuilder
    func body(content: Content) -> some View {
        if !items.isEmpty {
            content
        } else {
            placeholder
        }
    }
}

struct ContentView: View {

    @State var countries: [String] = [] // Data source

    var body: some View {
        List(countries) { country in
            Text(country)
                .font(.title)
        }
        .modifier(EmptyDataModifier(
            items: countries,
            placeholder: Text("No Countries").font(.title)) // Placeholder. Can set Any SwiftUI View
        ) 
    }
}

Also via extension can little bit improve the solution:

extension List {
    
    func emptyListPlaceholder(_ items: [Any], _ placeholder: AnyView) -> some View {
        modifier(EmptyDataModifier(items: items, placeholder: placeholder))
    }
}

struct ContentView: View {

    @State var countries: [String] = [] // Data source

    var body: some View {
        List(countries) { country in
            Text(country)
                .font(.title)
        }
        .emptyListPlaceholder(
            countries,
            AnyView(ListPlaceholderView()) // Placeholder 
        )
    }
}

If you are interested in other ways you can read the article

Related