Instance Method

frame(width:height:alignment:)

Positions the view within an invisible frame with the specified size.

Declaration

func frame(width: CGFloat? = nil, height: CGFloat? = nil, alignment: Alignment = .center) -> some View

Parameters

width

A fixed width for the resulting view. If width is nil, the resulting view assumes this view’s sizing behavior.

height

A fixed width for the resulting view. If width is nil, the resulting view assumes this view’s sizing behavior.

alignment

The alignment of this view inside the resulting view. alignment applies if this view is smaller than the size given by the resulting frame.

Return Value

A view with fixed dimensions of width and height, for the parameters that are non-nil.

Discussion

Use this method to specify a fixed size for a view’s width, height, or both. If you only specify one of the dimensions, the resulting view assumes this view’s sizing behavior in the other dimension.

For example, the first ellipse in the following code is rendered in a fixed 200 by 100 frame. The second ellipse has only its height fixed, at 100; its width still expands to fill its parent’s dimensions.

VStack {
    Ellipse()
    .fill(Color.purple)
    .frame(width: 100, height: 100)
    Ellipse()
    .fill(Color.blue)
    .frame(height: 100)
}

If this view is smaller than the resulting frame in either dimension, alignment specifies this view’s alignment within the frame.

Text("Hello world!")
.frame(width: 200, height: 200, alignment: .topLeading)
.border(Color.gray)

See Also

Sizing a View

func fixedSize() -> View

Fixes the view at its ideal size.

func fixedSize(horizontal: Bool, vertical: Bool) -> View

Fixes the view at its ideal size in the specified dimensions.

func layoutPriority(Double) -> View

Sets the priority by which a parent layout should apportion space to the child.