WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED Independent buttons in loop

Forums > SwiftUI

I'm trying to make multiple buttons change color independently, scroll through three colors. I've got this far but the button you tap changes the values elsewhere.

Any ideas.

import SwiftUI

struct ContentView: View {

@State private var buttonNumberArray:[Int] = [98,99,100]
@State private var colorNumberArray:[Int] = [0,0,0]

var body: some View {

    VStack {
        ForEach(0..<buttonNumberArray.count, id: \.self) { forNumber in

            Text("\(colorNumberArray[forNumber])")

           Button("button number\(buttonNumberArray[forNumber])"){
              self.changeNumber(number: colorNumberArray[forNumber])
            }
            .padding()

        }

        VStack {
            Text("colorNumberArray \(colorNumberArray[0])")
            Text("colorNumberArray \(colorNumberArray[1])")
            Text("colorNumberArray \(colorNumberArray[2])")
        }

    }
}

func changeNumber(number:Int){

    if colorNumberArray[number] == 2 {
        colorNumberArray[number] = 0
    }else {
        colorNumberArray[number] += 1
    }
}

}

1      

There's information missing:

  • How do you set the color of the buttons?
  • How do you go from colorNumberArray to an actual color?

Before going into more details:

You are changing the values inside your array. So the items at each index get changed. Each time your @State changes, it renders the views again.

You also do not provide details on how : "...but the button you tap changes the values elsewhere."

Always remember that when you ask questions, those able and willing to help don't know the rest of your code... the more details, the easier it becomes to help. 😉

2      

I've just solved it, took me ages. I haven't done they code to change the colors yet but the value in colorNumberArray will be used to set the background color of the button, @NigelGee helped with that part. Hopefully i'll have the whole code tomorrow. I'll put it on here as there might be other beginners struggling with this type of problem.

1      

This works, buttons change through three colors independently of each other .

import SwiftUI

struct ContentView: View {

@State private var buttonNumberArray:[Int] = [98,99,100]
@State private var colorNumberArray:[Int] = [0,0,0]

var body: some View {

    VStack {
        ForEach(0..<colorNumberArray.count ) { forNumber in

            Text("\(colorNumberArray[forNumber])")
            Text("\(forNumber)")
            Button(action: {
                changeNumber(number: forNumber)
            }, label: {
                Text("Button number\(buttonNumberArray[forNumber])")
            })
            .buttonStyle(ChangeColorButton(numberForBackground: colorNumberArray[forNumber]))
            .padding()
        }

    VStack {
        Text("colorNumberArray 0  \(colorNumberArray[0])")
        Text("colorNumberArray 1  \(colorNumberArray[1])")
        Text("colorNumberArray 2 \(colorNumberArray[2])")
    }
    }

}
struct ChangeColorButton: ButtonStyle {
    let colors: [Color] = [.gray, .green, .red]
    let numberForBackground: Int

    func makeBody(configuration: Configuration) -> some View {

        configuration.label
            .frame(width: 25, height: 25, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
            .padding()
            .background(colors[numberForBackground])
    }

}

func changeNumber(number:Int){

    if colorNumberArray[number] == 2 {
        colorNumberArray[number] = 0
    }else {
        colorNumberArray[number] += 1
    }
}

}

struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }

1      

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

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.