Swift SwiftUI CoreData 过滤数据 2

预览

Swift SwiftUI CoreData 过滤数据 2_第1张图片


Code

import SwiftUI
import CoreData

struct HomeSearchView: View {
    @Environment(\.dismiss) var dismiss
    
    @State private var search_value = ""

    @FetchRequest(
        entity: Bill.entity(),
        sortDescriptors: [
            NSSortDescriptor(keyPath: \Bill.c_at, ascending: false)
        ],
        predicate: nil,
        animation: .default
    )
    private var bills_filter: FetchedResults<Bill>
    
    private func SearchByNameOrSurname() {
        let predicate: NSPredicate?
        if !search_value.isEmpty {
            let namePredicate = NSPredicate(format: "name CONTAINS %@", search_value)
            let moneyyPredicate = NSPredicate(format: "money CONTAINS %@", search_value)
            predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [namePredicate, moneyPredicate])
        } else {
            predicate = nil
        }
        bills_filter.nsPredicate = predicate
    }
    
    
    
    var body: some View {
        NavigationStack {
            VStack {
                HStack {
                    HStack {
                        Image(systemName: "magnifyingglass")
                        TextField("分类、金额、备注", text: $search_value)
                            .onChange(of: search_value) { _ in
                                SearchByNameOrSurname()
                            }
                    }
                    
                    Button {
                        search_value = ""
                        dismiss()
                    } label: {
                        Text("取消")
                    }
                }
                
                List {
                    Section(header: Text("匹配条数 \(bills_filter.count)")) {
                        ForEach(bills_filter) { bill in
                            HStack {
                                Text(bill.emoji ?? "Unknown bill emoji")
                                Text(bill.name ?? "Unknown bill name")
                                Spacer()
                                Text("\(bill.moneyy ?? 0.0)")
                            }
                        }
                    }
                }
            }
            .navigationTitle("搜索")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
}

struct HomeSearchView_Previews: PreviewProvider {
    static var previews: some View {
        HomeSearchView()
    }
}


喜欢或对你有帮助,点个赞吧,自己先点个嘿嘿。
有错误或者疑问还请评论指出。
我的个人网站 点击访问 hongweizhu.com。

END

你可能感兴趣的:(SwiftUI,Swift,CoreData,CoreData,Swift,SwiftUI)