.overlay()

Published Feb 18, 2023Updated Apr 10, 2023
Contribute to Docs

The .overlay() layers the specified views in front of another view.

Syntax

Text("This text will have views layered over top of it.")
  .overlay(alignment) {
    // Subviews here
}

The .overlay() modifier method takes two parameters to create a ZStack to group the foreground views:

  • alignment specifies where to position the foreground views.
  • content is used to declare the views to add to the foreground, stacked in the order listed. The last view appears at the front of the stack.

Using the .overlay() modifier method without any specified parameter results in the default behavior of the modifier: the foreground views will be centered on the view.

Example

The following example uses the .overlay modifier to lay a star and a Circle over a Color view:

import SwiftUI
struct ContentView: View {
var body: some View {
Color.blue
.frame(width: 200, height: 200)
.overlay {
Circle()
.frame(width: 100, height: 100)
Image(systemName: "star.fill")
.foregroundStyle(Color.yellow)
}
}
}

This will display the following:

SwiftUI Overlay Modifier Example

All contributors

Looking to contribute?

Learn SwiftUI on Codecademy