ViewThatFits

A view that adapts to the available space by providing the first child view that fits.

ComponentiOS 16.0+macOS 13.0+tvOS 16.0+watchOS 9.0+ViewThatFits in SwiftUI

Declaration

React
import { ViewThatFits } from 'swiftui-react-native';
Swift
@frozen nonisolated struct ViewThatFits<Content> where Content : View

Initializers

One SwiftUI initializer backs <ViewThatFits>.

React
<ViewThatFits
  in?: SwiftUI.AxisSet
>
  children?: ReactNode
</ViewThatFits>
Swift
nonisolated init(
    in axes: Axis.Set = [.horizontal, .vertical],
    @ContentBuilder content: () -> Content
)
  • A set of axes to constrain children to. The set may contain Axis/horizontal, Axis/vertical, or both of these. ViewThatFits chooses the first child whose size fits within the proposed size on these axes. If axes is an empty set, ViewThatFits uses the first child view. By default, ViewThatFits uses both axes.

    Default `[.horizontal, .vertical]`Swift in axes: Axis.Set

  • childrenReactNode

    Content. Strings become Text; React Native views are laid out by Yoga and placed by SwiftUI.

    Swift content: () -> Content

Also takes the common view props: modifiers, style and testID.

Overview

ViewThatFits evaluates its child views in the order you provide them to the initializer. It selects the first child whose ideal size on the constrained axes fits within the proposed size. This means that you provide views in order of preference. Usually this order is largest to smallest, but since a view might fit along one constrained axis but not the other, this isn't always the case. By default, ViewThatFits constrains in both the horizontal and vertical axes.

The following example shows an UploadProgressView that uses ViewThatFits to display the upload progress in one of three ways. In order, it attempts to display:

The progress views are fixed to a 100-point width.

struct UploadProgressView: View {
    var uploadProgress: Double

    var body: some View {
        ViewThatFits(in: .horizontal) {
            HStack {
                Text("\(uploadProgress.formatted(.percent))")
                ProgressView(value: uploadProgress)
                    .frame(width: 100)
            }
            ProgressView(value: uploadProgress)
                .frame(width: 100)
            Text("\(uploadProgress.formatted(.percent))")
        }
    }
}

This use of ViewThatFits evaluates sizes only on the horizontal axis. The following code fits the UploadProgressView to several fixed widths:

VStack {
    UploadProgressView(uploadProgress: 0.75)
        .frame(maxWidth: 200)
    UploadProgressView(uploadProgress: 0.75)
        .frame(maxWidth: 100)
    UploadProgressView(uploadProgress: 0.75)
        .frame(maxWidth: 50)
}

From Apple’s SwiftUI documentation. Code samples there are Swift.

Relationships

Conforms to

  • View

See also

More in Views.