Sunday, August 14, 2022
HomeiOS Developmentios - Points with coloring the tapped on image picture in a...

ios – Points with coloring the tapped on image picture in a ForEach


I’ve a view that shows a number of image photos. When a logo picture is tapped on by the person I need the image picture to show blue. When the person faucets on one other image picture I need the outdated image picture to return to its authentic coloration and the brand new image picture to show blue.

The present conduct, nevertheless, is that the beforehand tapped on image photos stay blue. This isn’t the conduct I need. I solely need the one, presently chosen image picture to be blue.

import SwiftUI

struct IconsView: View {
    
    non-public let columns = [ GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()) ]
    
    non-public let icons = [ "a.circle", "b.circle", "c.circle", "d.circle", "e.circle", "f.circle", "g.circle", "h.circle",
                          "i.circle" ]
    
    var physique: some View {
        LazyVGrid(columns: columns) {
            ForEach(icons, id: .self) { merchandise in
                IconsSubView(strIcon: merchandise)
            }
        }
    }
}
import SwiftUI

struct IconsSubView: View {
    
    let strIcon: String
    @State non-public var isSelectedIcon = false
    
    var physique: some View {
        Picture(systemName: strIcon).tag(strIcon)
            .foregroundColor(isSelectedIcon == true ? Colour.blue : Colour.major)
            .font(.system(measurement: 50))
            .onTapGesture(carry out: {
                isSelectedIcon.toggle()
                print(strIcon)
            })
    }
}

Beforehand I had the 2 views in a single. The issue I used to be having again then was that after I tapped on one image picture ALL of them would flip blue.

import SwiftUI

struct IconsViewOld: View {
    
    @State non-public var isSelectedIcon = false
    
    non-public let columns = [ GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()) ]
    
    non-public let icons = [ "a.circle", "b.circle", "c.circle", "d.circle", "e.circle", "f.circle", "g.circle", "h.circle",
                          "i.circle" ]
    
    var physique: some View {
        LazyVGrid(columns: columns) {
            ForEach(icons, id: .self) { merchandise in
                Picture(systemName: merchandise)
                    .foregroundColor(isSelectedIcon == true ? Colour.blue : Colour.major)
                    .font(.system(measurement: 50))
                    .onTapGesture(carry out: {
                        isSelectedIcon.toggle()
                        print(merchandise)
                    })
            }
        }
    }
}

I might respect any assist.

Thanks.

I‘m utilizing XCode 13.4.1 and iOS 15.5

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments