I have a JournalView which displays a ScrollView-VStack list of events. Whenever a new event item is added to the list it ends up drawing the view multiple times.
import SwiftUI
import Foundation
struct JournalView: View {
@EnvironmentObject var dailyData: DailyData
var body: some View {
GeometryReader { geometry in
VStack(spacing: 5) {
ZStack(alignment: .bottomTrailing) {
dailyEventsView()
.visibility(!showAddEventsMenu)
VStack(alignment: .trailing) {
AddEventsMenuButton()
}
}
}
}
}
private func dailyEventsView() -> some View {
return ScrollView {
VStack(alignment: .center) {
ForEach(dailyData.events) { event in
switch event.type {
case .WATER:
WaterCardView(eventID: event.id, dailyData: dailyData)
default:
HStack {}
}
}
}
}
}
private func AddEventsMenuButton() -> some View {
Button(action: {
dailyData.addEvent(event: Event(type: .WATER))
}){
Image(systemName: "plus.circle")
.resizable()
.frame(width: 40, height: 40)
.gradientForeground(colors: [.yellow, .orange, .red])
}
}
}
This is what the DailyData.swift file looks like
import SwiftUI
class DailyData: ObservableObject {
private let TAG: String = "\(DailyData.self)"
@Published var events: [Event] = []
public func addEvent(event: Event) {
Log.d(tag: TAG, msg: "addEvent(event = \(event.id))")
let index = eventIndex(eventID: event.id)
if index == -1 {
Log.d(tag: TAG, msg: "No previous index, adding...")
// Selection sort insert based on date/time.
if 0 == events.count {
Log.d(tag: TAG, msg: "No previous events, adding at index zero.")
events.append(event)
} else {
for i in 0 ..< events.count {
if event.dateTime >= events[i].dateTime {
events.insert(event, at: i + 1)
}
}
}
}
Log.d(tag: TAG, msg: "WaterMacroProgress = \(macroWaterProgress)")
}
public func eventIndex(eventID: String) -> Int {
for i in 0 ..< events.count {
if eventID == events[i].id {
return i
}
}
return -1
}
}
When you add the first two events, everything is all good, but then once I started to add the third even and so forth it starts to draw the view multiple times...
This is the output of pressing the "add" button THREE times: