Building a Calorie Tracking iOS App

Perfect. You're designing this in a very intuitive and actionable way — love the minimalist manual tracking idea.Let’s implement the following:


✅ What We’ll Do

  • Add two buttons: +100 (red) for eating, and -100 (green) for exercise.
  • Flip the direction of the timer so that it counts down — toward deficit — not up.
  • Display the current net calories:
  • Positive (surplus): red
  • Negative (deficit): green
  • Zero: gray or neutral

🧠 New Formula

We track:

ini

netCalories = -passiveBurned + manualOffset

Where:

  • passiveBurned increases over time from BMR
  • manualOffset increases/decreases via buttons

🧱 Updated Code

Replace your ContentView.swift with this:

swift

import SwiftUI struct ContentView: View { // User-defined BMR let bmrKcalPerDay: Double = 2000 let kcalPerSecond: Double // Time tracking @State private var timerStartDate: Date = Date() // Calories manually added or subtracted @State private var manualOffset: Double = 0.0 // Timer let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect() init() { kcalPerSecond = bmrKcalPerDay / 86400.0 } var body: some View { VStack(spacing: 30) { Text("Net Calories Today") .font(.title) // Net = -passive + manual Text(String(format: "%.0f kcal", netCalories)) .font(.system(size: 48, weight: .bold, design: .monospaced)) .foregroundColor(netCaloriesColor) .padding() HStack(spacing: 30) { Button(action: { manualOffset += 100 }) { Text("+100") .font(.title2) .padding() .frame(minWidth: 100) .background(Color.red.opacity(0.2)) .foregroundColor(.red) .cornerRadius(12) } Button(action: { manualOffset -= 100 }) { Text("-100") .font(.title2) .padding() .frame(minWidth: 100) .background(Color.green.opacity(0.2)) .foregroundColor(.green) .cornerRadius(12) } } } .onAppear { timerStartDate = Date() } .onReceive(timer) { currentTime in // Updates automatically each second } } // Passive burned since app started var passiveBurned: Double { Date().timeIntervalSince(timerStartDate) * kcalPerSecond } // Net = manual - passive (i.e., how far into deficit or surplus you are) var netCalories: Double { manualOffset - passiveBurned } // Color based on surplus or deficit var netCaloriesColor: Color { if netCalories 0 { return .red // surplus } else { return .gray } } }


🧪 Try It

When you run the app now:

  • The number will start at 0 and slowly go negative (good).
  • Tap +100 if you eat — it pushes the number more positive (bad).
  • Tap -100 if you exercise — it makes the number more negative (good).
  • The color reflects that:
  • 🔴 Red for surplus
  • 🟢 Green for deficit
  • ⚪️ Gray at zero

💡 Bonus Idea for Later

You can show a goal target (e.g. -500 kcal/day), or a progress ring, or save per-day history using UserDefaults or Core Data.Let me know when you’re ready to persist this or build a nice graph / history view!