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