Your First iOS & SwiftUI App: Polishing the App

Mar 1 2022 Swift 5.5, iOS 15, Xcode 13

Part 1: SwiftUI Views & View Modifiers

8. Fill & Stroke Shapes

Lesson Complete

Play Next Lesson
Next
Save for later
About this episode
See versions

See forum comments
Cinema mode Mark as Complete Download course materials
Previous episode: 7. Challenge: Extract Views Next episode: 9. SFSymbols

This video was last updated on Mar 1 2022

If we look back to Luke’s design, we can see that the Hit Me button has a nice little white border around the edges. How can we accomplish that affect with SwiftUI?

Luckily, it’s actually pretty easy, thanks to SwiftUI’s powerful support for creating shapes, and then filling and stroking them with colors.

Before we start to see how we can apply shapes to solve the particular challenge of the Hit Me button, let’s learn the basics of drawing shapes with SwiftUI.

Create a new SwiftUI View file named Shapes.swift.

Replace body of Shapes with this:

VStack {
  Circle()
}
.background(Color.green)

Show how you can apply a view modifier to set a specific width and height:

.frame(width: 200, height: 100)

Add this:

.fill(Color.blue)

Remove the fill, and stroke instead:

.stroke(Color.blue, lineWidth: 20)

Fix with an inset:

.inset(by: 10)

Show better way:

.strokeBorder(Color.blue, lineWidth: 20.0)

Add other shapes in:

RoundedRectangle(cornerRadius: 20)
  .fill(Color.blue)
  .frame(width: 200, height: 100)
Capsule()
  .fill(Color.blue)
  .frame(width: 200, height: 100)
Ellipse()
  .fill(Color.blue)
  .frame(width: 200, height: 100)

Explain that you can’t use strokeBorder and fill, but you can use stroke and fill.

OK, now that you understand the basics of working with shapes with SwiftUI, how can we use this to add the border around the Hit Me Button?

One way of doing this is to simply draw a rounded rectangle with a white stroke on top of the hit me button.

We could do that with a ZStack, but I want to show you an alternative way: by using the overlay view modifier. Let’s dive in.

Go back to ContentView.swift, and add this to the bottom of the view modifiers for HitMeButton:

.overlay(
  RoundedRectangle(cornerRadius: 21.0)
    .strokeBorder(Color.white, lineWidth: 2.0)
)