I'm doing FetchRequest
@Environment(\.managedObjectContext) var managedObjContext
@FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)])
var day: FetchedResults<Item>
And then I put it in Charts, but Swift Charts need Plottable, and it seems to me that there is no way to convert it.
Help, please!
Trying to do this kind of thing, but it doesn't work. Mistake: Cannot convert value of type '() -> BarMark' to expected argument type '(FetchedResults.Element) -> BarMark' (aka '(Item) -> BarMark'). I should convert my core data to Plottable, I think, ad I don't no how.
import SwiftUI
import Charts
struct ChartView: View {
@Environment(\.managedObjectContext) var managedObjContext
@FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)]) var day: FetchedResults<Item>
@State var low = 0
@State var top = 0
@State var ir = 0
@State var date = Date()
var body: some View {
Chart(day) {
BarMark(
x: .value("Day", low),
y: .value("Sales", top)
)
}
}
}
I've found pretty easy solution, code:
struct ChartView: View {
@Environment(\.managedObjectContext) var managedObjContext
@FetchRequest(sortDescriptors: [SortDescriptor(\.date, order: .reverse)]) var items: FetchedResults<Item>
@State var low = 0
@State var top = 0
@State var ir = 0
func getDate(date: Date)->String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd"
let stringDate = dateFormatter.string(from: date)
return stringDate
}
var body: some View {
Chart {
ForEach(items.prefix(5)) { item in
var dateInitial = getDate(date:(item.date!))
LineMark(x: .value("date", "\(item.date)"), y: .value("hours slept", item.top))
.cornerRadius(8.0)
.annotation(position: .overlay, alignment: .top, spacing: 2.0) {
Text("\(item.top, specifier: "%.2f")")
.font(.system(size:10))
.foregroundColor(.white)
.fontWeight(.bold)
}
}
}
}
}
struct ChartView_Previews: PreviewProvider {
static var previews: some View {
ChartView()
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.