UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Help: DAY 47 I have no idea how to accomplish updating count update

Forums > 100 Days of SwiftUI

I feel like I have tried everything, I am racking my brain but it feels like the more I try the more confused I get. I accomplished storing to UserDefault and creating views. But not sure how to accomplisth the updating of count in detailed view.

//
//  ContentView.swift
//  Habit-Tracker
//
//  Created by Alex on 2021-09-27.
//

import SwiftUI

struct SheetView: View {
    @Environment(\.presentationMode) var presentationMode
    @ObservedObject var habit = Habit()
    @Binding var test: [Activities]

    @State private var name = ""
    @State private var description = ""
    var countNum = 0
        var body: some View {

            VStack{
                Spacer()
                    .frame(maxHeight: 350)
                Text("Add a new habit")
                    .font(.system(size: 30)).bold()

                VStack{
                    HStack(alignment: .center, spacing: 25){
                        Text("Name of Activity")
                        TextField("Hiking", text: $name)
                    }
                    HStack(alignment: .center, spacing: 30){
                        Text("Description")
                        TextField("Once a week", text: $description)

                    }
                }
                .font(.system(size: 22))
                .padding(10)
                Spacer()
                    .frame(maxHeight: 50)

                Button("add habit") {
                    var newItem = Activities(id: UUID() , name: name, count: description, countNum: countNum)
                    test.append(newItem)
//                    habit.items.append(newItem)

//                    print(test)
                    self.presentationMode.wrappedValue.dismiss()
                }
                .font(.system(size: 25).bold())
                .frame(width:150, height: 50, alignment: .center)
                .background(Color.blue)
                .foregroundColor(.white)

                .clipShape(RoundedRectangle(cornerRadius: 25.0))
                Spacer()
                    .frame(maxHeight: 250)
            }
            .padding(25)

        }
}

struct DescriptionView: View{
    @ObservedObject var activities = Habit()
//    @Binding var habit: Habitr
    var newItem: [Activities]
    var testItem: [Activities] = [Activities]()

    var id: UUID = UUID.init()
    var name: String = ""
    var description: String = ""
    @State var countNum: Int = 0
    @State var new_count: Int = 0

    init(newItem: [Activities]){
//        self.habit: Habit = Habit()
        self.newItem = newItem
//        self.testItem = activities.items
        print("test items \(testItem)")
       var i = 0
        for item in newItem{

            self.id = item.id
            self.name = item.name
            self.description = item.count
            self.countNum = item.countNum

            countNum = self.countNum
            i += 1
        }
        countNum = self.countNum
        print("self \(self.countNum)")
        print("countNum \(countNum)")
    }

    var body: some View{

        VStack{

                Text("\(name)")
                    .padding()
                    .font(.largeTitle.bold())
                    .foregroundColor(.white)
                Spacer()
                    .frame(maxHeight: 40)
                Text("\(description)")
                    .font(.body.bold())
                Spacer()
                .frame(maxHeight: 40)

            Text("Current times: \(countNum)")
                .font(.system(size: 25).bold())
            Text("add to count: \(countNum)")
                .font(.system(size: 25).bold())
            Stepper("", value: $countNum, in: 0...100)
                    .frame(alignment: .center)
                    .labelsHidden()

            Button("count up"){
                print("not a match")
//                print(newItem)
                var finalArray: [Activities] = []
                var newArray = newItem
                for item in newItem{
                    var index = 0
                    if var match = newItem.first(where: {$0.id != item.id}){
//                        habit.items[index].countNum += 1
                        print("got a match")
//                        match.countNum += 1
                        print("match \(match)")
                        activities.items.append(Activities(id: UUID() , name: newItem[index].name, count: newItem[index].count, countNum: newItem[index].countNum + 1))
//                        activities.items.remo
//                        activities.items.append(newArray)
                        print(activities.items)
                        break
                    }
                    else{
                        print("did not  match")
                    }
                    index += 1
                }
//                activities.items.append(newItem[1])
//                ForEach i in0...newItem.count{
//
//                    activities.items[i].append(newItem[i])
//                }
                print(activities.items)

            }

        }
        .frame(width: 400, height: 300, alignment: .center)
        .background(Color(red: 137/255, green: 196/255, blue: 244/255, opacity: 0.5))

        .clipShape(RoundedRectangle(cornerRadius: 25.0))

        Spacer()
    }

}

struct Activities: Identifiable, Codable{
    var id = UUID()
    var name: String
    var count: String
    var countNum: Int
}

class Habit: ObservableObject{
    @Published var items = [Activities]()
    {

    didSet{
//            self.save()
//            print("setting a new var in user default")
            let encoder = JSONEncoder()

            if let encoded = try?
                encoder.encode(items){
                UserDefaults.standard.set(encoded, forKey: "Items")
            }
        }
    }
    init(){
        if let items = UserDefaults.standard.data(forKey: "Items"){
            let decoder = JSONDecoder()
            if let decoded = try? decoder.decode([Activities].self, from: items){
                self.items = decoded
//                print(decoded)
                return
            }
        }
        self.items = []
    }

    func save() {
        if let encoded = try? JSONEncoder().encode(items) {
            print("encoding data.....")
            UserDefaults.standard.set(encoded, forKey: "Items")
        }
    }

}
struct ContentView: View {
    @State var newItems: [Activities]
    @State private var showingSheet = false

    var body: some View {

        NavigationView{
            ZStack{
                VStack(){
                    HStack(){
                        Text("Habbit Rabbit")
                            .font(.system(size: 30)).bold()

                        Text("🐰").font(.system(size: 50))
                    }.offset(y: -40)
                    Spacer()

                    VStack{
                        List(newItems){ item in
                            NavigationLink(destination: DescriptionView(newItem: newItems)){
                            Text(item.name)
                            }
                        }
                        .listStyle(InsetListStyle())
                    }

                }
                .sheet(isPresented: $showingSheet){
                    SheetView(test: $newItems)
                }
            }

            .navigationViewStyle(StackNavigationViewStyle())
            .navigationBarItems(trailing: Button(action: {

                self.showingSheet.toggle()

            }) {
                Image(systemName: "plus")
                    .font(.system(size: 25.0).bold())
                    .padding(.trailing, 10)
//
            })
            .padding(.leading, 0)

            .font(.system(size: 40).bold())

        }

    }
    init(){
        if let items = UserDefaults.standard.data(forKey: "Items"){
            let decoder = JSONDecoder()
            if let decoded = try? decoder.decode([Activities].self, from: items){
                newItems = decoded
                UserDefaults.standard.removeObject(forKey: "Items")
//                print(decoded)

                return
            }
        }
        self.newItems = []
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

3      

Hey @KynanB, With some help from your original code, I think I have solved your problem.

One of your errors is here:

@ObservedObject var habit = Habit()

This should be:

@ObservedObject var habit: Habit

Except in your ContentView where it should be:

@StateObject var habit = Habit()

Another error is that you are passing in an array of [Activities], you need to use the Habit Class, and you need to use Habit.items for things.

The third major thing is, when in the DescriptionView, you need to find the activity in the array ( using: firstIndex(of:)), then replace it with the new activity (new because you have changed the counter value).

I hope that makes sense??

I've re-written your code, if you need any/all then I can share.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

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.