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

how to get the index of an array element from within the element

Forums > SwiftUI

So lets say I have an array of rectangles:

var myArray = [Rectangle()]

this array has say, four elements, so myArray[0] to myArray[3], each is drawn on screen in a view

each of those rectangles has an .onTapGesture {} method how would I, with the .onTapGesture get the index of the rectangle I am clicking on? So if Im clicking on the rectangle that is myArray[1], how do i get that index?

code for building the array:

func buildRectArray(arraySize: Int) -> [Rectangle] {
    var theRectArray = [Rectangle()]
    let theCounter = arraySize * arraySize - 1
    for i in 1...theCounter {
        theRectArray.append(Rectangle())
    }
    return theRectArray
}

code for showing the array:

Grid (horizontalSpacing: 0, verticalSpacing: 0) {
            ForEach(0..<gridSize, id: \.self) { row in
                GridRow{
                    ForEach(0..<gridSize, id: \.self) { col in
                        GeometryReader { proxy in
                            thisArray[aCount]
                             .foregroundColor(.gray)
                             .overlay(Text("\(row) \(col)"))
                             .border(Color.black)
                             .bold()
                             .onTapGesture {
                                 //this is where I want it to get the index of itself
                             }
                             .onAppear(perform: {
                                     aCount += 1
                             })
                        }
                    }
                }
            }
        }

2      

See you answer in your other post increment an integer in a ForEach loop

2      

Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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

Reply to this topic…

You need to create an account or log in to reply.

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.