TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: View not updating despite @published being used

Forums > SwiftUI

All of th ehabits have a Progress bar, and values for how far along they are. Right now I've got some swipe actions attached to each HabitListView in the list. The buttons chang the Core Data values, but those changes are only reflected upon closing the app and re-launching. Does anyone have any idea on why the @Publisher variable isn't doing it's job?

List Items:

List {
    ForEach(habits, id:\.id) { habit in
        HabitListView(habit: habit)
        .swipeActions(edge: .leading) {
                Button {
                    withAnimation {
                        habitManager.addOneToValue(habit: habit)
                        try? moc.save()
                    }
                } label: {
                    Text("+1")
                        .foregroundColor(.white)
                }
                .tint(.blue)

                Button {
                    withAnimation {
                        habitManager.addTwentyToValue(habit: habit)
                        try? moc.save()
                    }
                } label: {
                    Text("+2")
                        .foregroundColor(.white)
                }
                .tint(.blue)
            }
    }
}

HabitListView:

struct HabitListView: View {
    @Environment(\.colorScheme) var colorScheme
    @StateObject private var viewModel: ViewModel

    var body: some View {
        ZStack {
            ProgressBar(progress: viewModel.habit.percentComplete)
                .stroke(viewModel.habit.wrappedColor, lineWidth: 5)
                .offset(x: 0, y: 37.5)

            HStack {
                Image("\(viewModel.habit.wrappedIcon)")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .blending(color: viewModel.habit.wrappedColor)
                    .frame(width: 60)
                    .padding(.leading, 7)
                VStack {
                    Text(viewModel.habit.wrappedTitle)
                        .bold()
                        .font(.title3)
                    Text(viewModel.habit.wrappedAbout)
                        .font(.callout)
                }

                Spacer()

                VStack {
                    Text("\(viewModel.habit.wrappedCurrentCompletionValue.formatted()) / \(viewModel.habit.wrappedTargetValue.formatted())")
                        .bold()
                        .font(.title3)
                        .foregroundColor(viewModel.habit.wrappedColor)
                    Text(viewModel.habit.wrappedUnitType)
                        .bold()
                        //.font(.title3)
                }
                .frame(width: 90)
                .padding(.trailing)
            }
        }
        .frame(width: viewModel.deviceSize.width * 0.9, height: 80)
        .background(color())
        .clipShape(RoundedRectangle(cornerRadius: 12))
        .overlay(
            viewModel.habit.wrappedCurrentStreak > 1 ?
            ZStack {
                Image("flames")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .blending(color: Color.streakFire)
                    .frame(width: 35)
                    .offset(y: -3)
                Text("\(viewModel.habit.wrappedCurrentStreak)")
                    .foregroundColor(.black)
                    .bold()
                    .font(.system(size: 500))
                    .minimumScaleFactor(0.01)
                    .frame(width: 20, height: 20)
            }
                .offset(x: viewModel.deviceSize.width * -0.43, y: -30)
            :
            nil
        )
    }//

    func color() -> Color {
        colorScheme == .dark ? Color.darkModeButton : Color.lightModeButton.opacity(0.5)
    }

    init(habit: Habit) {
        _viewModel = StateObject(wrappedValue: ViewModel(habit: habit))
    }
}

HabitListView-ViewModel

extension HabitListView {
    class ViewModel: ObservableObject {
        let deviceSize: CGRect = UIScreen.main.bounds
        @Published var habit: Habit

        init(habit: Habit) {
            self.habit = habit
        }
    }
}

2      

Solved it!

I changed this:

extension HabitListView {
    class ViewModel: ObservableObject {
        let deviceSize: CGRect = UIScreen.main.bounds
        @Published var habit: Habit

        init(habit: Habit) {
            self.habit = habit
        }
    }
}

To this:

extension HabitListView {
    class ViewModel: ObservableObject {
        let deviceSize: CGRect = UIScreen.main.bounds
        @ObservedObject var habit: Habit

        init(habit: Habit) {
            self.habit = habit
        }
    }
}

Then, in my View, I changed how I'm calling my ViewModel from @StateObject to @ObservedObject:

From:

@StateObject private var viewModel: ViewModel

init(habit: Habit) {
        _viewModel = StateObject(wrappedValue: ViewModel(habit: habit))
    }

To this:

@ObservedObject private var viewModel: ViewModel

init(habit: Habit) {
        _viewModel = ObservedObject(wrappedValue: ViewModel(habit: habit))
    }

After these changes, the view started updating properly!

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 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.