ios – How can I update a counter for each `View` a SwiftUI `ForEach` builds?


I think I titled this question accurately. LOL

This may be a repeat, but I don’t understand how to apply what I’ve seen to my situation.

I have X number of points (10 – 1,000+) to plot as iOS 17 Annotations on a MapKit map in SwiftUI. Creating these annotation points can take some time, so I want to display a loading status popup that counts up as each annotation is created (Currently being done in a SwiftUI ForEachbuilder‘).

Currently, I am only aware of incrementing an @State variable to do this.

I am beginning to grasp that ForEach is a builder of Views and not a loop … and it’s closure can only contain code that results in a View/s(?).

I also get that currentCount += 1 does not result in a View.

What I do not yet grasp is where/how to increment/track something that will keep my popup in sync.

I tried to put all of my ForEach closure code in a function (as suggested elsewhere), but I could not figure out the syntax to make it work.

Here’s my code…

//🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣
//🟣    Display a Map with 10 - 1,000  annotations.
//🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣🟣
ZStack {
   Map {
      ForEach(myPoints
         .filter { point in return point.normalizedScoreInt >= Int(severityOfPointsToMap) ? true : false }) {p in
            Annotation("", coordinate: CLLocationCoordinate2D(latitude: p.latitude, longitude: p.longitude), anchor: .topTrailing) {
               if p.normalizedScoreInt >= 5 {
                  ArrowStarView(bumpColor: Color(p.heatmapColor))
               } else {
                  BallArrowView(bumpColor: Color(p.heatmapColor), rotation: Double(p.headingDeg))
               }
               currentCount += 1 //  ← ← THIS IS WHAT I WANT (so that the counter in my popup updates. 
            }
         }
    }
   if debugStatusIsVisible {
      VStack {
         DebugStatusView(debugStatusIsVisible: $debugStatusIsVisible, whatsBeingCounted: $whatsBeingCounted, currentCount: $currentCount, totalToBeCounted: $numberOfPointsToMap)
         Spacer()
      }
   }
}

I’ve googled this and reviewed 10+ results, and they all seem to be the same problem from the same individual (good job to them for trying to get their answer).

However, I don’t think it is the same situation that I have.

This is something I find myself wanting to do all of the time. Can’t I write some kind of extension to ForEach to allow me to be able to update a counter⁉️ LOL

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img