UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Returning the number of records in a SwiftData model back to a parent view after filtering/deleting/adding

Forums > SwiftUI

I have a List() of items, with the ability to sort and search. To handle the dynamic nature of the querying I have a separate View file allowing me to mess around with the Query itself.

I would like to show the number of records currently displayed in the list within the parent view, and the number should dynamically update when filtering/deleting/adding items.

I have attempted this via a combination of @State var in the parent and @Binding var in the child view.

It mostly seems to work, but this could be by luck, as I am a newbie with SwiftUI and SwiftData.

The count of items is correct when launching the app and when deleting records (which makes me think I am sort of on the right track). However I have not got it working when adding new records just yet.

While stopping to look at how to approach getting the number right when adding, I am wondering if I have over engineered this, as I seem to be repeating the idea of setting the "counter" in numerous places, which tells me I am probably approaching this in the wrong way.

Do you have some advice as to firstly getting the counter working correctly using my approach, and then second, any advice on how to simplify this (assuming I have over engineered it to start with)?

My code is shown below.

Model files:

//------------
//  Item.swift
//------------
import Foundation
import SwiftData

@Model
class Item: Identifiable {
    let id: UUID = UUID()
    var title: String
    var username: String
    var password: String

    init(title: String = "", username: String = "", password: String = "") {
        self.title = title
        self.username = username
        self.password = password
    }
}

//------------------
//  SortOption.swift
//------------------
import Foundation

enum SortOption: String, CaseIterable {
    case ascending = "A-Z"
    case descending = "Z-A"
}

Main content view (parent)

//-------------------
//  ContentView.swift
//-------------------
import SwiftUI
import SwiftData

struct ContentView: View {
    @Environment(\.modelContext) private var modelContext

    @State private var showingItemDetailView: Bool = false
    @State private var sortOption: SortOption = .ascending
    @State private var searchText: String = ""
    @State private var counter: Int = 0

    var body: some View {
        NavigationStack {
            SortedListView(sortOption: sortOption, searchText: searchText, counter: $counter)
                .navigationTitle("My Passwords \(counter)")
                .toolbar {
                    ToolbarItem {
                        Button {
                            showingItemDetailView = true
                        } label: {
                            Image(systemName: "plus.circle.fill")
                        }
                    }
                    ToolbarItem(placement: .bottomBar) {
                        Picker("", selection: $sortOption) {
                            ForEach(SortOption.allCases, id:\.self) { sortOption in
                                Text(sortOption.rawValue)
                            }
                        }
                        .pickerStyle(.segmented)
                    }
                }
                .sheet(isPresented: $showingItemDetailView) {
                    ItemDetailView(item: Item())
                }
                .searchable(text: $searchText)
        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: Item.self)
}

Sorted Item view (child view)

//----------------------
//  SortedListView.swift
//----------------------
import SwiftUI
import SwiftData

struct SortedListView: View {
    @Environment(\.modelContext) private var modelContext
    @Query private var items: [Item]

    let sortOption: SortOption
    let searchText: String
    @Binding var counter: Int

    init(sortOption: SortOption, searchText: String, counter: Binding<Int>) {
        self.sortOption = sortOption
        self.searchText = searchText
        self._counter = counter

        switch self.sortOption {
        case .ascending:
            if searchText.isEmpty {
                _items = Query(sort: \.title)
            } else {
                _items = Query(filter: #Predicate { $0.title.localizedStandardContains(searchText) ||
                    $0.username.localizedStandardContains(searchText) ||
                    $0.password.localizedStandardContains(searchText) }, sort: \.title)
            }
        case .descending:
            if searchText.isEmpty {
                _items = Query(sort: \.title, order: .reverse)
            } else {
                _items = Query(filter: #Predicate { $0.title.localizedStandardContains(searchText) ||
                    $0.username.localizedStandardContains(searchText) ||
                    $0.password.localizedStandardContains(searchText) }, sort: \.title, order: .reverse)
            }
        }
    }

    var body: some View {
        List() {
            ForEach(items) { item in
                NavigationLink {
                    ItemDetailView(item: item)
                } label: {
                    Text("\(item.title) (\(items.count))")
                }
            }
            .onDelete(perform: deleteItems)
        }
        .onAppear(perform: { counter = items.count })
    }

    func deleteItems(_ indexSet: IndexSet) {
        for index in indexSet {
            let item = items[index]
            modelContext.delete(item)
            try? modelContext.save()
        }
        counter = items.count
    }
}

#Preview {
    @State var counter: Int = 0
    return SortedListView(sortOption: .ascending, searchText: "", counter: $counter)
        .modelContainer(for: Item.self)
}

Item view (where we add/update items)

//----------------
//  ItemView.swift
//----------------
import SwiftUI
import SwiftData

struct ItemDetailView: View {

    @Environment(\.dismiss) var dismiss
    @Environment(\.modelContext) private var modelContext

    @State var item: Item

    var body: some View {
        NavigationStack {
            Form {
                TextField("Title:", text:$item.title)

                TextField("Username:", text:$item.username)
                    .textInputAutocapitalization(.never)

                TextField("Password:", text:$item.password)
                    .textInputAutocapitalization(.never)

            }
            .toolbar {
                ToolbarItem(placement: .navigationBarLeading) {
                    Button("Cancel") {
                        dismiss()
                    }
                }

                ToolbarItem(placement: .navigationBarTrailing) {
                    Button("Save") {
                        modelContext.insert(item)
                        try? modelContext.save()
                        dismiss()
                    }
                }
            }
            .navigationBarBackButtonHidden()

        }
    }
}

#Preview {
    ContentView()
        .modelContainer(for: Item.self)
}

I would appreciate any advice. Thank you.

   

I found a work around. I show the counter within the view that handles the query, rather than attempting to hand it back to the parent view.

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.