|
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 |
SPONSORED Building and maintaining in-app subscription infrastructure is hard. Luckily there's a better way. With RevenueCat, you can implement subscriptions for your app in hours, not months, so you can get back to building your app.
Sponsor Hacking with Swift and reach the world's largest Swift community!
You need to create an account or log in to reply.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.