GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Day 47: Habit Tracker | Unexpected behavior when incrementing completion of an Habit

Forums > 100 Days of SwiftUI

Hi everyone! I just completed the "Habit Tracker" challenge.

To solve this, I added the "plus" buttom to the main view and used the 'Habits' View Model to find the index of the Item and add one to it and it works when I press the buttom but also when I press the Row and I wasn't expecting this last behavior, does anyone have any idea of why this is happening?

Here's the piece of code:

List {
                    ForEach(habitTypes, id: \.self) { type in
                        Section(type.rawValue) {
                            ForEach(habits.items) { item in
                                if item.type == type {

                                    HStack {
                                        HabitView(habit: item)

                                        Spacer()

                                        Button {
                                            if let index = habits.index(of: item) {
                                                habits.addTimeCompleted(at: index)
                                            }
                                        } label: {
                                            Image(systemName: "plus")
                                        }
                                    }

                                }
                            }
                            .onDelete(perform: removeItems)
                        }
                    }

                }

Thanks in advance for the input!

2      

Hi @KeyBarreto! If you could provide more details on ViewModel and HabitView it would be easier for others to understand what is happining in your code. With such limited information it is difficult to say what might be the reason for such behavior.

2      

Yes, sure @ygeras. I tried to add a Screenshot too but I couldn't find how.

This is my "Habit View":

struct HabitView: View {

    var habit: HabitItem

    var body: some View {
        HStack {

            VStack(alignment: .leading) {
                Text(habit.name)
                    .font(.title3.bold())
                Text(habit.description)
            }

            Spacer()

            Text("\(habit.timesCompleted)")
                .font(.largeTitle.bold())

        }
        .padding(EdgeInsets(top: 10, leading: 20, bottom: 10, trailing: 30))

    }
}

struct HabitView_Previews: PreviewProvider {
    static var previews: some View {
        HabitView(habit: HabitItem(name: "Habit Name", description: "Habit Description", timesCompleted: 3, type: .academic))
    }
}

And this is the Habits ViewModel:

class Habits: ObservableObject {
    @Published var items = [HabitItem]() {
        didSet {
            let encoder = JSONEncoder()

            if let encoded = try? encoder.encode(items) {
                UserDefaults.standard.set(encoded, forKey: "items")
            }
        }
    }

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

    @Published var predefinedHabitsList: [HabitItem] = [
        HabitItem(name: "Read", description: "30 minutes of reading daily", timesCompleted: 1, type: .academic),
        HabitItem(name: "Sleep", description: "Sleep at least 7 hours a day", timesCompleted: 1, type: .physical),
        HabitItem(name: "Drink water", description: "Have a glass of water", timesCompleted: 1, type: .nutrition),
        HabitItem(name: "Keep a schedule", description: "Answer e-mails", timesCompleted: 1, type: .professional),
        HabitItem(name: "Lower anxiety", description: "Meditate", timesCompleted: 1, type: .spiritual)
    ]

    func index(of item: HabitItem) -> Int? {
        for i in items.indices {
            if items[i].id == item.id {
                return i
            }
        }

        return nil
    }

    func addTimeCompleted(at index: Int) {
        items[index].timesCompleted += 1
    }
}

2      

Add a buttonStyle modifier to your Button; perhaps .buttonStyle(.borderless) would be appropriate for your use case.

2      

Thanks @roosterboy ! That worked! So adding a button to a VStack or HStack will make the entire Stack a button (Clickable) if I don't use the 'borderless' modifier?

Also, 'borderless' sounds counterintuitive, the documentation says: "A button style that doesn’t apply a border." Or maybe it's because English it's not my main language but it sounds like exactly the opposite. Would you mind to explain further?

Thanks again!

2      

@Key wants to understand the buttonStyle modifier.

Also, 'borderless' sounds counterintuitive, the documentation says: "A button style that doesn’t apply a border."
Or maybe it's because English it's not my main language but it sounds like exactly the opposite. Would you mind to explain further?

Here's a small example for you to run in Playgrounds to illustrate three types of button border styles.
The borderless style just floats above the background. It is not surrounded by a button-shaped box.

import SwiftUI
import PlaygroundSupport

// basic push button
struct PushMeButton: View {
    var title = "Empurre-me" // <-- isso está correto?
    var body: some View {
        Button {
            print("Tapped.") // foi divertido
        } label: {
            Label(title, systemImage: "touchid")
                .font(.system(size: 40))
        }.padding(.bottom)
    }
}
// A view to show three button types.
struct ButtonView: View {
    var body: some View {
        VStack {
            // Three basic buttons with styles applied
            PushMeButton()
                .buttonStyle(.bordered)          // <-- Button shaped box
            PushMeButton(title: "Imprensa")
                .buttonStyle(.borderedProminent) // <-- Button shaped box
            PushMeButton(title: "Boop Me")
                .buttonStyle(.borderless)        // <-- No box. Floats above background
        }.background(.yellow.opacity(0.6))
    }
}
// Run this line in Playgrounds
PlaygroundPage.current.setLiveView(ButtonView())

2      

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 and A/B test your entire paywall UI 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.