Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11781

SwiftUI: Toggle for individual items of ForEach

$
0
0

Using ForEach, I want to create individual Toggles for each row. Right now, the @State binding toggles all of the items at the same time, and I can't figure out how to separate them.

In the code below, I put a hard-coded array, but it really comes from an ever-changing .json file. Therefore, I need the ForEach and the binding to be dynamic.

This post on hiding List items and this post on problems with List rows were helpful, but I couldn't make the binding work for my project. I'm on day 2 trying to figure this out, and none of what I've found online addresses this specific question.

Below is a small example of my code that reproduces my challenge. The dynamic data from the array comes from a .json file.

import SwiftUIstruct GreekWords: Codable, Hashable {    var greekWordArray = ["Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"]    // The array data comes from a dynamic .json file}struct ContentView: View {    var greekWords: GreekWords    @State private var wordToggle = false    var body: some View {        VStack(spacing: 0) {            ForEach(greekWords.greekWordArray, id: \.self) { word in                Toggle(word, isOn: $wordToggle)            }        }        .padding(.horizontal)    }}

I expect this is a simple solution, so I thank you in advance for any help. Also, I would appreciate any direction you might point me to better learn SwiftUI. I've tried all the Apple tutorials and books and the 100 days of SwiftUI on HackingWithSwift.

Cheers!


Viewing all articles
Browse latest Browse all 11781

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>