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

Day 47. Problems incrementing the completion count in Habit Tracker app

Forums > SwiftUI

Not sure why whenever i want to increment the completion count in the detailed view, it increments in the detailed view but when i go back to the previous content view page and click into the detailed view, the count resets to 0. is there a way for me to rectify this?

ContentView.swift

//
//  ContentView.swift
//  Habit Tracker
//
//  Created by YeetdSkra on 2/3/21.
//

import SwiftUI

struct Activity: Identifiable, Codable {
    var id = UUID()
    let Title : String
    let ActivityType : String
    let Description : String
    var Count : Int

    public mutating func incrementAmount() {
        self.Count += 1
    }
}

class ActivityArray: ObservableObject {
    // Array to hold activities and stores them into UserDefaults
    @Published var items = [Activity]() {
        // Save changes, when activity is added or deleted
        didSet {
            let encoder = JSONEncoder()
            // Encodes activities and stores it into the UserDefaults
            if let encoded = try? encoder.encode(items) {
                UserDefaults.standard.set(encoded, forKey: "Items")
            }
        }
    }

    // Automatically loads data from UserDefaults
    init() {
        if let items = UserDefaults.standard.data(forKey: "Items") {
            let decoder = JSONDecoder()
            // Decode data from UserDefaults
            if let decoded = try? decoder.decode([Activity].self, from: items) {
                self.items = decoded
                return
            }
        }
        // if decoding didnt go through, activity array will be empty
        self.items = []
    }
}

struct ContentView: View {
    @ObservedObject var activities = ActivityArray()
    @State private var showingAddActivity = false

    var body: some View {
        NavigationView {
            List {
                ForEach(activities.items) { item in
                    NavigationLink(destination: HabitView(activity: item)) {
                    HStack {
                        VStack(alignment: .leading) {
                            Text(item.Title)
                                .font(.headline)
                            Text(item.ActivityType)
                        }
                    }
                        Spacer()
                    }
                }
                .onDelete(perform: removeItems)
            }
            .navigationBarTitle("Habitual")
            .navigationBarItems(trailing:
                Button(action: {
                    self.showingAddActivity = true
                }) {
                    Image(systemName: "plus")
                }
            )
            .sheet(isPresented: $showingAddActivity) {
                addActivityView(activities: self.activities)
            }
        }
    }

    func removeItems(at offsets: IndexSet) {
        activities.items.remove(atOffsets: offsets)
    }
}

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

HabitView.swift

//  Created by YeetdSkra on 4/3/21.
//
// Detailed View of the Habit

import Foundation
import SwiftUI

struct HabitView: View {
    @State var activity: Activity

    var body: some View {
        VStack {
            Text(activity.Title)
            Text(activity.ActivityType)
            Text(activity.Description)
            Text("Completion Count:\(activity.Count)")
            Spacer()
            Button("Increment completion count by 1") {
                activity.incrementAmount()
            }
        }
    }
}

struct HabitView_Previews: PreviewProvider {
    static var previews: some View {
        HabitView(activity: ActivityArray().items[0])
    }
}

AddActivityView.swift

//
//  AddActivityView.swift
//  Habit Tracker
//
//  Created by YeetdSkra on 4/3/21.
//

import Foundation
import SwiftUI

struct addActivityView: View {
    @ObservedObject var activities: ActivityArray
    @State private var Title = ""
    @State private var type = "Routine"
    @State private var Description = ""
    @State private var Count = 0
    @Environment(\.presentationMode) var presentationMode

    static let types = ["Work","Hygiene"]

    var body: some View {
        NavigationView {
            Form {
                TextField("Activity Title", text: $Title)
                Picker("Type", selection: $type) {
                    ForEach(Self.types, id: \.self) {
                        Text($0)
                    }
                }
                TextField("Description of activity", text: $Description)
            }
            .navigationBarTitle("Add a new activity")
            .navigationBarItems(trailing: Button("Save") {
                let item = Activity(Title: self.Title, ActivityType: self.type, Description: self.Description, Count: self.Count)
                self.activities.items.append(item)
                self.presentationMode.wrappedValue.dismiss()
            })
        }
    }
}

struct AddView_Previews: PreviewProvider {
    static var previews: some View {
        addActivityView(activities: ActivityArray())
    }
}

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.