|
I want to change color of buttons when clicked inside forEach statement. I want to apply different color for different button. Can anyone help me out. Thanks in advance |
|
If you use |
|
@twostraws, Here is my code:
Actually i want to change color the buttons as colors array above. For eg: if a user first selects any button then the color of that button should be organe, and if the user selects another button then it should be green and so on. The user can select upto 7 buttons and if 7 different buttons are selected, then they should have 7 different color. The problem in the code above is that if a user first selects any button, then color of that button is orange and if selects 2nd button, then both becomes green. Thanks :) |
|
Ok so the issue is that you have a single array to store ALL the buttons that are currently 'on' and you are setting the SAME color for all of them.
That basically says for ALL of the button in the selectedButtons array - color them the current colorIndex - or color them white. So what you need is to have an array of 'Buttons' which have their OWN color associated with them For example
In you view you can then create a State which will hold onto them
And update your updateSelectedButtons func to use that instead
So here we are saying that IF we have a button with the selected index then REMOVE it from the array Otheriwse APPEND it to the list and set the Color of THAT button to the current colorIndex and then increment the colorIndex - rotate if too large. Then your body for the view is simpler too - we have a helper function (really should be a custom modifier - but hey I was rushed)
This will return the color from the struct in the array OR White
so full code is
I am sure that @twostraws will have a cleaner way of doing it but this works at least |
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.
Sponsor Hacking with Swift and reach the world's largest Swift community!
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.
Link copied to your pasteboard.