.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 SwiftUIstruct 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:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn SwiftUI on Codecademy
- Skill path
Build iOS Apps with SwiftUI
Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.Includes 7 CoursesWith CertificateBeginner Friendly13 hours - Free course
Learn Swift
A powerful programming language developed by Apple for iOS, macOS, and more.Beginner Friendly12 hours