I wan to get the last 7 entries from the model mood. I just want the list contain not more than 7 entries and its is the last 7 of it. I tried for loop and foreach loop but still get an error.
if selectedTab == "LAST 7 ENTRIES"{
ForEach(self.entryController.moods, id: \.id )
{mood in
NavigationLink(destination: EntryDetailView(entryController: self.entryController, mood: mood)) {
HStack{
VStack {
Text(mood.monthString)
.font(.title2)
.fontWeight(.bold)
.foregroundColor(mood.emotion.moodColor)
Text("\(mood.dayAsInt)")
.font(.title2)
.fontWeight(.bold)
.foregroundColor(mood.emotion.moodColor)
}
RowView(mood: mood)
}
}
}.onDelete { (index) in
self.entryController.deleteMood(at: index)
}
}
This is my Entry Controller and the model
@Published var moods: [Mood] = [];
struct Mood: Codable, Equatable, Identifiable {
var id = UUID()
let emotion: Emotion
var activity: String?
var comment: String?
let date: Date
init(emotion: Emotion, activity: String?, comment: String?, date: Date) {
self.emotion = emotion
self.activity = activity
self.comment = comment
self.date = date
}
}
func loadFromPersistentStore() {
// Plist -> Data -> Stars
let fileManager = FileManager.default
guard let url = persistentFileURL, fileManager.fileExists(atPath: url.path) else { return }
do {
let data = try Data(contentsOf: url)
let decoder = PropertyListDecoder()
moods = try decoder.decode([Mood].self, from: data)
} catch {
print("error loading stars data: \(error)")
}
}
CodePudding user response:
Here is an approach for you, your question does not contain needed codes to answer it, however in this example you can find a way for your issue:
struct ContentView: View {
let array: [Int] = Array(1...28)
var body: some View {
ForEach(array.indices, id:\.self) { index in
if ((array.count - 7) < array[index]) {
Text("\(array[index])")
.padding()
}
}
}
}
CodePudding user response:
you could try something like this:
if (entryController.moods.count >= 7) {
ForEach((entryController.moods.endIndex-7)..<entryController.moods.endIndex, id: \.self) { ndx in
let mood = entryController.moods[ndx]
// ...
}
}
Note, you will have to adjust the index in the .onDelete