NEW: Nominations are now open for the 2019 Swift Community Awards! >>

How to draw a border inside a view

Paul Hudson    @twostraws   

Fully updated for Xcode 11.1

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(Color.blue, lineWidth: 50)

Because that doesn’t specify a frame, that circle will occupy the full width of the screen, and its 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(Color.blue, lineWidth: 50)

Now you’ll see that the left and right edges of the stroke are cut off, because they fall outside of the screen.

SAVE 20% ON iOS CONF SG The largest iOS conference in Southeast Asia is back in Singapore for the 5th time in January 2020, now with two days of workshops plus two days of talks on SwiftUI, Combine, GraphQL, and more! Save a massive 20% on your tickets by clicking on this link.

Similar solutions…

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift 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: 5.0/5