How do I pin a view to the edges of a screen?

Viewed 5167

How do I pin a view (in this case, a label/text) to an edge of a screen with SwiftUI? With Storyboards I would just use AutoLayout but that isn't available with SwiftUI.

enter image description here

4 Answers

You can do something like this

    VStack {
        HStack {
            Text("Label")
            Spacer()
        }
        Spacer()
    }

Spacer in VStack will make sure HStack is at the top, Spacer in HStack will make sure Text is all they way to the left. You can also solve this with alignments.

You can wrap your main content in a special container called GeometryReader. Its default size is the same as its parent so if it is the root view it will pin the contents to the screen edges like AutoLayout.

GeometryReader { in geometry
    YourContentView().frame(width: geometry.size.width, height: geometry.size.height)
}

In case anyone is here to find a way to pin a view x points from the top, you can do this:

VStack {
        Spacer()
            .frame(height: 40)
        Text("Space me")
        Spacer()
    }

You'll need both spacers. This can be a bit counter-intuitive if you're coming from Auto Layout but it's actually quite convenient. The spacer at the bottom of your VStack will "push" your VStack views from the default (i.e. centered) y position toward the top until it meets resistance – by default the top edge of the safe area. You can then push the resting point down by x points with the top spacer, giving a similar effect as Auto Layout's top constraint.

Use this modifier on your view

  .frame(minWidth: 0, maxWidth: .infinity,
         minHeight: 0, maxHeight: .infinity)

SwiftUI uses minimum needed space for any view, to increase it you may use different approaches depending on the situation. Also it's possible to use relativeSize() modifier, but I didn't get yet when it works

Related