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 have older iOS apps and want to enhance them with modern SwiftUI features, check out my book Integrating SwiftUI into UIKit Apps. It provides detailed guidance on gradually adopting SwiftUI in your UIKit projects. Additionally, if you're eager to enhance your Swift programming skills, my latest book Swift Gems offers over a hundred advanced tips and techniques, including optimizing collections, handling strings, mastering asynchronous programming, and debugging, to take your Swift code to the next level.

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Enhance older apps with SwiftUI!$45

A detailed guide on gradually adopting SwiftUI in UIKit projects

Updated for iOS 18 and Xcode 16!

Integrating SwiftUI into UIKit Appsby Natalia Panferova

  • Upgrade your apps with new features like Swift Charts and Widgets
  • Support older iOS versions with effective backward-compatible strategies
  • Seamlessly bridge state and data between UIKit and SwiftUI using the latest APIs

Enhance older apps with SwiftUI!

A detailed guide on gradually adopting SwiftUI in UIKit projects

Integrating SwiftUI into UIKit Apps by Natalia Panferova book coverIntegrating SwiftUI into UIKit Apps by Natalia Panferova book cover

Integrating SwiftUI
into UIKit Apps

by Natalia Panferova

Updated for iOS 18 and Xcode 16!

$45