Your First iOS & SwiftUI App: Polishing the App

Mar 1 2022 · Swift 5.5, iOS 15, Xcode 13

Part 1: SwiftUI Views & View Modifiers

08. Fill & Stroke Shapes

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 07. Challenge: Extract Views Next episode: 09. SFSymbols
Transcript: 08. Fill & Stroke Shapes

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