Homework 7: Offset and label the green slice

Mastering SwiftUI led you through a long lesson on creating a pie chart with arcs enveloped by a ZStack. The code to make the whole pie is provided below, and your job is to offset one slice of the pie (an arc of course) and overlay it with a label. Feel free to use the book’s code (pages 90-93) as a reference or simply type along with the code below.

Complete Pie Chart Code

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack {
            Arc(startAngle: .degrees(0), endAngle: .degrees(90), clockwise: true)
                .fill(Color.blue)
            Arc(startAngle: .degrees(90), endAngle: .degrees(180), clockwise: true)
                .fill(Color.red)
            Arc(startAngle: .degrees(180), endAngle: .degrees(270), clockwise: true)
                .fill(Color.green)
            Arc(startAngle: .degrees(270), endAngle: .degrees(360), clockwise: true)
                .fill(Color.orange)
        }
    }
}

struct Arc: Shape {
    var startAngle: Angle
    var endAngle: Angle
    var clockwise: Bool
    func path(in rect: CGRect) -> Path {
        var p = Path()
        p.addArc(center: CGPoint(x: rect.midX, y: rect.midY),
                 radius: rect.width / 2,
                 startAngle: startAngle,
                 endAngle: endAngle,
                 clockwise: clockwise)
        p.addLine(to: CGPoint(x: rect.midX, y: rect.midY))
        p.closeSubpath()
        return p
    }
}

Your Task

Your goal is two-fold: pop the green slice outward from the center of the pie, and label it with a text overlay.

Target pie chart: green slice offset with label on top

Step 1: Offset the green slice

Add an .offset() modifier to the green Arc to push it away from the center. The green slice spans from 180° to 270°, which puts its midpoint at 225° — in the bottom-left direction. To push it outward, use a negative x value and a positive y value (e.g., .offset(x: -20, y: 20)). Adjust the values until the slice is clearly separated from the rest of the pie.

💡 Hint: Experiment with values between 10 and 40 for both x and y. A small offset looks subtle; a large one makes a dramatic effect.

Step 2: Overlay a text label

Once the green slice is offset, add a Text label that appears on top of it. There are two approaches:

  • Wrap the offset arc in its own ZStack: Replace the green Arc line with a ZStack that contains the arc and a Text view layered on top. The label will automatically center over the arc.
  • Add a Text to the outer ZStack: Add a separate Text to the main ZStack and give it its own .offset() to position it near the offsetted slice.

💡 Hint: The inner ZStack approach is more self-contained. The Text will appear at the visual center of the arc — which may not be perfect, but it’s close enough. Use .foregroundColor(.white) and a .font(.headline) to make the label readable against the green background.