← Back to archive

Development · SwiftUI

Understanding SwiftUI frames

Explore how width, height, and alignment affect the relationship between a view and its parent.

Read the Korean original on Velog ↗English translation

Development archive cover

It is tempting to think a frame simply resizes a view. A better starting point is that it adds another layout container between the parent and the content.

The frame area

Without an additional frame, the view participates in layout using its own sizing behavior.

Text("Hello, World!")
	.background(Color.red) // The text's own bounds

A fixed frame occupies the specified area and proposes a size to its content.

Text("Hello, World!")
	.background(Color.red) // The text's own bounds
    .frame(width: 200, height: 200) // The text's frame
	.background(Color.green)

Alignment

The frame's alignment determines where its content sits within that area.

Text("Hello, World!")
	.background(Color.red)
    .frame(width: 200, height: 200, alignment: .leading) // Leading alignment
	.frame(width: 200, height: 200, alignment: .center) // Center alignment
	.frame(width: 200, height: 200, alignment: .trailing) // Trailing alignment
	.background(Color.green)

Flexible frames

Minimum, ideal, and maximum dimensions allow the frame to adapt to the space offered by its parent.

Text("Hello, World!")
	.background(Color.red)
 	.frame(
		minWidth: 10, // Set the minimum width
        idealWidth: 300, // Set the ideal width
        maxWidth: .infinity, // Set the maximum width
        minHeight: 10, // Set the minimum height
        idealHeight: 300, // Set the ideal height
        maxHeight: .infinity, // Set the maximum height
        alignment: .center
        )

fixedSize asks a view to use its ideal size on the selected axes. The result depends on the content and modifier order; a view may extend beyond the space its parent proposes.

.fixedSize(horizontal: true, vertical: true)
← Back to archive