← Back to archive

Development · SwiftUI

Backgrounds and overlays in SwiftUI

Place content behind or in front of a base view, and understand alignment and modifier order.

Read the Korean original on Velog ↗English translation

Development archive cover

A background color and a foreground badge both add layers, but their placement and modifier order affect the result. Combining backgrounds and overlays makes those relationships easier to see.

Backgrounds

A background places content behind the modified view.

Text("Hello, World!")
	.background(
    	Color.red // Apply a color
        LinearGradient(
        gradient: Gradient(colors: [Color.red, Color.blue]),
        startPoint: .leading,
        endPoint: .trailing
        ) // Add a gradient
        Circle() // Add a shape
    )

Multiple backgrounds can be applied in sequence. The same is true of overlays.

Text("Hello, World!")
	.background(
        Circle()
        	.fill(
            	LinearGradient(
        		gradient: Gradient(colors: [Color.red, Color.blue]),
        		startPoint: .leading,
        		endPoint: .trailing
				)
			)
            .frame(width: 100, height: 100, alignment: .center)
	)
    .background(
        Circle()
        	.fill(
            	LinearGradient(
        		gradient: Gradient(colors: [Color.blue, Color.red]),
        		startPoint: .leading,
        		endPoint: .trailing
				)
			)
            .frame(width: 120, height: 120, alignment: .center)
	)

Overlays

An overlay places content in front of the modified view.

Circle()
	.fill(Color.pink)
    .frame(width: 100, height: 100)
    .overlay(
    	Text("A") // Add text
        	.font(.largeTitle)
            .foregroundColor(.white)
		Circle() // Add a shape
    )

An overlay's content can have its own overlay or background. Use alignment to position the added content relative to its base view.

Circle()
	.frame(width: 100, height: 100)
	.foregroundColor(.red)
	.overlay( // First overlay
		Circle()
			.frame(width: 40, height: 40)
			.overlay ( // Second overlay
				Text("1")
					.foregroundColor(.white)
			)
		, alignment: .bottomTrailing) // Align relative to the base view
← Back to archive