TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Accessing the index in ForEach... or how to alternate text color?

Forums > SwiftUI

@speg  

Salutations,

I am trying to render an array of strings in a scroll view.

I currently have:

 ForEach(output, id: \.self) { text in
                    Text(text)
                        .font(.system(.body, design: .monospaced))
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .foregroundColor(.white)

Now I would like to alternate the foregroundColor with a little index % 2 == 0 ? .white : .green however the closure does not give me the index.

Also, the array changes so I am not allowed to iterate over a range and use that as an index.

At this point, I'm thinking there's probably a better way to approach this than trying to force ths issue with ForEach.

3      

I think this should work.

ForEach(output.indices, id: \.self) { index in
                    Text(output[index])
                        .font(.system(.body, design: .monospaced))
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .foregroundColor (index % 2 == 0 ? .white : .green)

4      

@speg  

Thanks @ShadowDES , that worked! At first I thought it wouldn't because when I tried doing ForEach(0..<output.endIndex) it complained. Not sure exactly why this version works, perhaps becasue .indicies returns a different object each time?

2      

Might I suggest not using "ForEach" but a "For In" Loop. Below I used this technique to get the current index of a custom photo struct in an array of photos. Right after the photos are downloaded in the model I did a For In loop and assigned each photo the correct index to the index variable I made in the struct.


for index in self.photos.indices {

  print("\(index)")
  self.photos[index].photoIndex = index

}

2      

@creatorcody for in doesn't work in ViewBuilder, so it wouldn't help in this case - @speg is asking about ScrollView.

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.