读取和格式化日期时出现问题



我试图将CoreData中的一些数据读取到标准列表中,但在读取和格式化日期时遇到了问题。我似乎在荒草丛中!我有错误";"日期?"类型的值没有成员"getFormattedDate"其中我试图显示日期和错误";无法将"listView"类型的值转换为预期的参数类型"Date"在getFormattedDate函数的最后一行。

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)
}
}
}
@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
}()

相关内容

  • 没有找到相关文章

最新更新