显示来自CoreData SwiftUI的今天日期输入数据的唯一列表

时间:2020-06-07 15:59:45

标签: ios swift database core-data swiftui

有人可以解决这种情况下仅显示今天输入日期数据的代码。我将代码的详细信息放在下面(请阅读指南的注释),也许问题出在获取请求以及我要显示数据的每个内部滚动视图的上。如果需要任何细节,请让我知道

获取请求

  @FetchRequest(
    entity: ExpenseLog.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \ExpenseLog.date, ascending: false)
    ]
    ,predicate: NSPredicate(value: Calendar.current.isDateInToday(Date()))
) //here i dont know what to put to show the today inputted data
private var result: FetchedResults<ExpenseLog>

对于每个人

                            if self.result.count == 0
                        {
                            DaftarTransaksiEmpty()
                        }
                        else
                        {
                            VStack
                                {
                                    // i want to put list of the only today inputted data here
                                    ForEach(self.result)
                                    {
                                        (log: ExpenseLog) in



                                        ZStack{
                                        HStack(spacing: 16) {
                                                               CategoryImageView(category: log.categoryEnum)
                                                               VStack(alignment: .leading, spacing: 8) {
                                                                   Text(log.nameText).font(.headline)
                                                                   Text(log.dateText).font(.subheadline)
                                                               }
                                                               Spacer()
                                                               Text(log.amountText).font(.headline)

                                        } .padding(.vertical, 8) .padding(.horizontal,4)
                                          }

                                    }
                            }.background(Rectangle().foregroundColor(Color.init(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))).edgesIgnoringSafeArea(.all))
                        }

HomeView()(完整代码)

@Environment(\.managedObjectContext) var moc


@FetchRequest(entity: Profile.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Profile.namaUser, ascending: true),
    NSSortDescriptor(keyPath: \Profile.limitHarian, ascending: true),
    NSSortDescriptor(keyPath: \Profile.photo, ascending: true)
    ]
) var profiles : FetchedResults<Profile>

@State var photoUser : Data = .init(count: 0)


 @Environment(\.managedObjectContext)
 var context: NSManagedObjectContext



@FetchRequest(
    entity: ExpenseLog.entity(),
    sortDescriptors: [
        NSSortDescriptor(keyPath: \ExpenseLog.date, ascending: false)
    ]
    ,predicate: NSPredicate(value: Calendar.current.isDateInToday(Date()))
) //here i dont know what to put to show the today inputted data
private var result: FetchedResults<ExpenseLog>


let hour = Calendar.current.component(.hour, from: Date()) 

@State var pengeluaranhariini = "250.000"



enum HomeSheet{
    case Profile
    case Add
}

@State var isSheet : Bool = false
@State var homeSheet : HomeSheet = .Profile




var body: some View {


    GeometryReader { geometry in
        VStack
            {

                HStack{
                    ZStack
                        {
                            Image("kotakcardgreeting") .resizable()

                                .frame(width: geometry.frame(in: .global).width, height: geometry.frame(in: .global).height/4)
                                .offset(y: -50)

                            HStack{


                                                VStack(alignment: .leading){


                                                Text("\(getGreeting()),")
                                                        .font(.system(size: 22))
                                                        .fontWeight(.semibold).foregroundColor(Color.init(#colorLiteral(red: 1, green: 0.888686657, blue: 0.7034975886, alpha: 1))) .padding(.top, 40)

                                            ForEach(self.profiles, id: \.self)
                                                                                            { profilNama in
                                                Text("\(profilNama.namaUser ?? "")")
                                                          .font(.system(size: 22))
                                                          .fontWeight(.semibold).foregroundColor(Color.init(#colorLiteral(red: 1, green: 0.888686657, blue: 0.7034975886, alpha: 1))) .padding(.top, 1)
                                                    }


                                                      Text("Jangan lupa catat pengeluaranmu hari ini")
                                                          .font(.system(size: 17)).fontWeight(.semibold).foregroundColor(.white)
                                                          .padding(.top, 10)



                                                  }.padding()




                                Spacer()

                          ForEach(self.profiles, id: \.self)
                            { profilPhoto in
                                    VStack{
                                        Image(uiImage: UIImage(data: profilPhoto.photo ?? self.photoUser)!).resizable().frame(width: 55, height: 55).scaledToFit().overlay(Circle().stroke(Color.init(#colorLiteral(red: 1, green: 0.888686657, blue: 0.7034975886, alpha: 1)), lineWidth: 5)).clipShape(Ellipse()).shadow(color: Color.init(#colorLiteral(red: 1, green: 0.888686657, blue: 0.7034975886, alpha: 1)), radius: 5).onTapGesture {

                                        }.padding()


                                    }

                                }
                            }.offset(y: -60)


                            Image("bigaddbutton") .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: geometry.frame(in: .global).width/4, height: geometry.frame(in: .global).height/8) .onTapGesture {
                                    self.isSheet = true
                                    self.homeSheet = HomeSheet.Add

                            }
                            .padding(.top, 100)

                    }
                }

                Spacer()



                HStack {
                    ZStack {
                        Image("cardstatus") .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: geometry.frame(in: .global).width, height: geometry.frame(in: .global).height/4)
                        HStack
                            {
                                Spacer()
                                if self.result.count == 0
                                {
                                    Text(" ")
                                }
                                else
                                {
                                    Text("Rp \(self.pengeluaranhariini),00.")
                                                                       .font(.system(size: 20))
                                                                       .fontWeight(.bold).foregroundColor(.white) .multilineTextAlignment(.trailing) .padding(.top, 40)
                                }


                                Spacer()

                                if self.profiles.count == 0
                                {
                                    Text(" ")
                                }
                                else
                                {
                                    ForEach(self.profiles, id: \.self)
                                    { profilLimit in
                                        Text(("Rp \(profilLimit.limitHarian ?? ""),00."))
                                        .font(.system(size: 20)).fontWeight(.bold) .foregroundColor(.white) .multilineTextAlignment(.trailing)
                                        .padding(.top, 40)
                                    }

                                }

                                Spacer()
                        }

                    }
                }


                Spacer()

                HStack
                    {

                        Text("Daftar Pengeluaran Hari Ini")
                            .font(.system(size: 17)).fontWeight(.bold).foregroundColor(Color.init(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1))) .multilineTextAlignment(.leading)

                        Spacer()

                        Button(action: {
                            self.isSheet = true
                            self.homeSheet = HomeSheet.Add
                        }) {
                            Text("Tambah")
                                .font(.system(size: 17)).fontWeight(.bold).foregroundColor(Color.init(#colorLiteral(red: 0.1489486992, green: 0.390168488, blue: 0.555157125, alpha: 1))) .multilineTextAlignment(.leading)
                        }

                }.padding(.horizontal)

                ScrollView
                    {

                        if self.result.count == 0
                        {
                            DaftarTransaksiEmpty()
                        }
                        else
                        {
                            VStack
                                {
                                    // i want to put list of the only today inputted data here
                                    ForEach(self.result)
                                    {
                                        (log: ExpenseLog) in



                                        ZStack{
                                        HStack(spacing: 16) {
                                                               CategoryImageView(category: log.categoryEnum)
                                                               VStack(alignment: .leading, spacing: 8) {
                                                                   Text(log.nameText).font(.headline)
                                                                   Text(log.dateText).font(.subheadline)
                                                               }
                                                               Spacer()
                                                               Text(log.amountText).font(.headline)

                                        } .padding(.vertical, 8) .padding(.horizontal,4)
                                          }

                                    }
                            }.background(Rectangle().foregroundColor(Color.init(#colorLiteral(red: 1, green: 1, blue: 1, alpha: 1))).edgesIgnoringSafeArea(.all))
                        }








                }


        }.background(Rectangle().foregroundColor(Color.init(#colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1))).edgesIgnoringSafeArea(.all))

        .sheet(isPresented: self.$isSheet) {

                          if self.homeSheet == HomeSheet.Profile{
                            ProfileFilled().environment(\.managedObjectContext, self.moc)

            }
            else if self.homeSheet == HomeSheet.Add{
            LogFormView(context: self.context)

            }

        }



    }
}

这是我的ExpenseLog数据模型

ExpenseLog Entities

2 个答案:

答案 0 :(得分:0)

您可以在提取请求中使用谓词来过滤日期。像这样

@FetchRequest(entity: Profile.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Profile.namaUser, ascending: true),
NSSortDescriptor(keyPath: \Profile.limitHarian, ascending: true),
NSSortDescriptor(keyPath: \Profile.photo, ascending: true)
], predicate: NSPredicate(format: "date == %@", Date())) var profiles : FetchedResults<Profile>

答案 1 :(得分:0)

这个很好用。我将谓词格式化为“date <= %@ AND date >= %@”,这给了我今天的事件。

struct Today: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest var reminder: FetchedResults<CDReminder>
init(){
    var calendar = Calendar.current
    calendar.timeZone = NSTimeZone.local
    let dateFrom = calendar.startOfDay(for: Date()) // eg. 2016-10-10 00:00:00
    let dateTo = calendar.date(byAdding: .day, value: 1, to: dateFrom)
    let predicate = NSPredicate(format : "date <= %@ AND  date >= %@", dateTo! as CVarArg, dateFrom as CVarArg)
self._reminder = FetchRequest(
    entity: CDReminder.entity(),
    sortDescriptors: [NSSortDescriptor(keyPath: \CDReminder.date, ascending: false)],
    predicate: predicate)
}