UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.