BLACK FRIDAY: Save 50% on all my books and bundles! >>

How to draw a border inside a view

Paul Hudson    @twostraws   

Updated for Xcode 16.4

SwiftUI gives us both stroke() and strokeBorder() modifiers for drawing borders around shapes, and they have subtly different behavior:

  • The strokeBorder() modifier insets the view by half your border width then applies the stroke, meaning that the entire border is drawn inside the view.
  • The stroke() modifier draws a border centered on the view’s edge, meaning that half the border is inside the view and half outside.

Important: Both of these modifiers only apply to shapes – you can use stroke() and strokeBorder() with Circle, Rectangle, Capsule, and so on, but not with Text, Image or other non-shape views. If you want to draw a border around non-shape views, you should use the border() modifier instead – see “How to draw a border around a view”.

If you want to see strokeBorder() in action, try this:

Circle() .strokeBorder(.blue, lineWidth: 50) .frame(width: 200, height: 200) .padding()

Download this as an Xcode project

A thick blue circular ring.

Because that uses strokeBorder(), the 50-point blue stroke will be drawn entirely inside the circle.

If you aren’t quite sure of the difference from stroke(), try changing your code to this:

Circle() .stroke(.blue, lineWidth: 50) .frame(width: 200, height: 200) .padding()

Download this as an Xcode project

A larger thick blue circular ring.

Now you’ll see the circle looks bigger because the stroke is drawn half inside and half outside the circle.

Save 50% in my Black Friday sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further for less! Get my all-new book Everything but the Code to make more money with apps, get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn Swift Testing, design patterns, and more.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Everything but the Code Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Interview Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.9/5

 
Unknown user

You are not logged in

Log in or create account