NEW BOOK! SwiftUI Fundamentals: The essential guide to SwiftUI core concepts and APIs. Learn more ...NEW BOOK! SwiftUI Fundamentals:Master SwiftUI core concepts and APIs. Learn more...
Quick Tip Icon
Quick Tip

Set a shape as background in SwiftUI

SwiftUI provides a simple way to set a view's background to a shape, like a capsule or rounded rectangle, using the background(_:in:fillStyle:) modifier. This avoids the need to clip the background or separately define and fill a shape.

Here's an example:

Text("Hello, world!")
    .font(.title)
    .fontWeight(.semibold)
    .padding(22)
    .background(
        Color.yellow.gradient,
        in: Capsule()
    )

In this case, the capsule filled with a subtle yellow gradient is layered behind the text using background(Color.yellow.gradient, in: Capsule()).

iPhone screen displaying text with a yellow capsule in the background iPhone screen displaying text with a yellow capsule in the background

This convenience method works with shapes that conform to the InsettableShape protocol, like Capsule, Rectangle, Circle, and RoundedRectangle.


If you want to build a strong foundation in SwiftUI, my new book SwiftUI Fundamentals takes a deep dive into the framework’s core principles and APIs to help you understand how it works under the hood and how to use it effectively in your projects.

For more resources on Swift and SwiftUI, check out my other books and book bundles.

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

Deepen your understanding of SwiftUI!$35

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentalsby Natalia Panferova

  • Explore the key APIs and design patterns that form the foundation of SwiftUI
  • Develop a deep, practical understanding of how SwiftUI works under the hood
  • Learn from a former Apple engineer who worked on widely used SwiftUI APIs

Deepen your understanding of SwiftUI!

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

SwiftUI Fundamentals

by Natalia Panferova

$35