读取和格式化日期有问题

时间:2020-10-08 23:37:52

标签: swiftui ios14 xcode12

我正在尝试从CoreData读取一些数据到标准列表中,但是在读取和格式化日期时遇到了麻烦。我似乎杂草丛生!我出现错误“类型为“日期”的值?没有成员'getFormattedDate'“,我要在其中显示日期,并且在getFormattedDate函数的最后一行显示错误“无法将'listView'类型的值转换为预期的参数类型'Date'”。

struct listView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    
    let categories = ["AAA", "BBB","CCC","DDD"]
    
    @FetchRequest(
        entity: CurrTrans.entity(),
        sortDescriptors: []
    ) var currTrans: FetchedResults<CurrTrans>
    
    var body: some View {
        
        List {
            ForEach(currTrans, id: \.self) { item in
                VStack {
                    let date = item.entryDT
                    Text(date.getFormattedDate())
                      
                    // display category
                    if item.entryCat != nil {
                        Text("Category: \(categories[Int(item.entryCat)])")
                    } else {
                        Text("")
                    
                    // display description
                    if item.entryDsc != nil {
                        Text("\(item.entryDsc!)")
                    } else {
                        Text("")
                    }
                }
            }
        }
    
    
        func getFormattedDate() -> String {
            let dateformat = DateFormatter()
            dateformat.dateFormat = "d MMM HH:mm"
            return dateformat.string(from: self)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

@objc(Transaction)
public class Transaction: NSManagedObject {
    static let categoryStringsByCategoryID = ["AAA", "BBB","CCC","DDD"]
    func categoryString() -> String{
         return Transaction.categoryStringsByCategoryID[self.categoryID]
    }
}

struct ListView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    
    @FetchRequest(sortDescriptors: []) var transactions: FetchedResults<Transaction>
    
    var body: some View {
        
        List {
            ForEach(transactions) { transaction in
                VStack {
                    Text("\(transaction.timestamp!, formatter: transactionFormatter)")
                    // display category
                    
                    Text("Category: \(transaction.categoryString)")
                    
                    // display description
                    Text("\(transaction.entryDescription ?? "")")
                }
            }
        }
    }
}

private let transactionFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .medium
    return formatter
}()