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

SOLVED: How to create items in items.

Forums > SwiftUI

please. I need to create some items, save them, then link to each item and create other items in it. for example, I create individual cities and then add individual streets in those cities. and I want everything to be editable. well thank you.

2      

@rabrez asks for the entire 100 days of lessons summarised in a single post!

I need to create some items, save them, then link to each item
and create other items in it. for example, I create individual cities
and then add individual streets in those cities.
and I want everything to be editable.

You'd like this answered in one post?

@twoStraws has created a terrific series of lessons 📘and videos 🎥, along with challenging assignments that cover these exact topics and more!

He's one of the best SwiftUI instructors around and even HE hasn't been able to cover your requirements in ONE lesson. It will take several lessons to cover these! Maybe even 💯 days of lessons. 😳

Hope you plan to start with Day 1 and work your way through his excellent programme. Trust us! @twoStraws will cover each one of your requirements with humor 🤣 and fun exercises 🤸.

His requirements are you must code ⌨️ everyday 📅, and take each day one at a time!

Good Luck!

Keep Coding

2      

I would recomend that you follow @Obelix advice as in there is a project that has User Name (instead use City Names) and Addresses.

Simple struct

struct City {
    var name: String
    var streets: [Street]

    struct Street {
        var name: String
    }
}

2      

perfect thanks

2      

I can't help myself How do I add new people to the array? I think that it is necessary to index the family array and then append people under index of family... i don't know how

import SwiftUI

struct Family: Codable, Identifiable {
    var id = UUID()
    let name: String
    var peoples: [People]
}

struct People: Codable, Identifiable {
    var id = UUID()
    let name: String
    let age: Int
}
class Families: ObservableObject {
    @ Published var families = [Family]() {
        didSet {
            if let encoded = try? JSONEncoder().encode(families) {
                UserDefaults.standard.set(encoded, forKey: "Items")
            }
        }
    }

    init() {
        if let savedItems = UserDefaults.standard.data(forKey: "Items") {
            if let decodedItems = try? JSONDecoder().decode([Family].self, from: savedItems) {
                families = decodedItems
                return
            }
        }

        families = []
    }
}

struct NewView: View {

    @ObservedObject  var family: Families

    @State private var name = "jozo"
    @State private var age = 11

    var body: some View {
        NavigationView{
            List{

            }
            .navigationTitle("nove")
            .toolbar {
                Button("save") {
                    let people = People(id: UUID(),name: name, age: age)
                    family.families.peoples.append(people)

                }
            }
        }
    }
}

struct NewView_Previews: PreviewProvider {
    static var previews: some View {
        NewView(family: Families())
    }
}

2      

this is problem

family.families.peoples.append(people)

2      

Your logic should at least be like so

struct NewView: View {
    @ObservedObject  var model: Families

    @State private var family = ""
    @State private var name = "jozo"
    @State private var age = ""

    var body: some View {
        VStack {
            GroupBox {
                TextField("Family", text: $family)
                TextField("Name", text: $name)
                TextField("Age", text: $age)
            }
            .textFieldStyle(.roundedBorder)

            Button("save") {
                var family = Family(name: family, peoples: [People]()) // <-- You need to create a family first
                let person = People(name: name, age: Int(age)!) // <-- Then you create a person
                family.peoples.append(person) // <-- You add a person to a family
                model.families.append(family) // <-- You append family to families

            }
        }
    }
}

2      

i need create list where i create an save many families(for example) then i need create navigation link from them and create people under each of them

2      

I would prefer to still refactor it. But as a starting point can be something like this. If comments needed can do it tomorrow.

struct ContentView: View {
    @StateObject private var model = Families()
    var body: some View {
        NavigationStack {
            FamilyView(model: model)
        }
    }
}

struct FamilyView: View {
    @ObservedObject var model: Families
    @State private var showAddFamily = false

    var body: some View {
        List {
            ForEach($model.families) { family in
                NavigationLink {
                    FamilyMembersView(people: family.peoples, familyName: family.name.wrappedValue)
                } label: {
                    Text(family.name.wrappedValue)
                }
            }
        }
        .sheet(isPresented: $showAddFamily) {
            AddNewFamilyView(model: model)
        }
        .toolbar {
            Button("Add Family") {
                showAddFamily.toggle()
            }
        }
        .navigationTitle("Families")
    }
}

struct FamilyMembersView: View {
    @Binding var people: [People]
    @State private var showAddFamilyMember = false
    let familyName: String

    var body: some View {
        List {
            ForEach(people) { person in
                NavigationLink {
                    PersonDetailView(person: person)
                } label: {
                    Text(person.name)
                }
            }
        }
        .sheet(isPresented: $showAddFamilyMember) {
            AddPersonView(people: $people)
        }
        .toolbar {
            Button("Add Member") {
                showAddFamilyMember.toggle()
            }
        }
        .navigationTitle(familyName)
        .navigationBarTitleDisplayMode(.inline)
    }
}

struct PersonDetailView: View {
    var person: People

    var body: some View {
        Text("Name: \(person.name)")
        Text("Age: \(person.age) years old")
    }
}

struct AddNewFamilyView: View {
    @Environment(\.dismiss) var dismiss
    @ObservedObject  var model: Families
    @State private var familyName = ""

    var body: some View {
        NavigationStack {
            VStack {
                GroupBox {
                    TextField("Name of the family", text: $familyName)
                }
                .textFieldStyle(.roundedBorder)

                Button("Save") {
                    let newFamily = Family(name: familyName, peoples: [])
                    model.families.append(newFamily)
                    dismiss()
                }
                .buttonStyle(.borderedProminent)
                Spacer()
            }
            .toolbar {
                Button("Close") {
                    dismiss()
                }
            }
        }
    }
}

struct AddPersonView: View {
    @Binding var people: [People]
    @Environment(\.dismiss) var dismiss
    @State private var name = ""
    @State private var age = ""

    var body: some View {
        NavigationStack {
            VStack {
                GroupBox {
                    TextField("Name", text: $name)
                    TextField("Age", text: $age)
                }
                .textFieldStyle(.roundedBorder)

                Button("Save") {
                    let newPerson = People(name: name, age: Int(age)!)
                    people.append(newPerson)
                    dismiss()
                }
                .buttonStyle(.borderedProminent)
                Spacer()
            }
            .toolbar {
                Button("Close") {
                    dismiss()
                }
            }
            .navigationTitle("Add new member")
            .navigationBarTitleDisplayMode(.inline)
        }

    }
}

2      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

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.