SwiftUI .overlay()

tefyfernandez's avatar
Published Feb 18, 2023Updated Apr 10, 2023
Contribute to Docs

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

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours

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

Contribute to Docs

Learn SwiftUI on Codecademy

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours