10

Does anyone know how does SwiftUI render in terms of coordinate space? It doesn't look like the frame's origin is now at the 0, 0 in the left top corner. For example adding a Text with a modifier would offset the label outside of a view.

var body: some View {
    Text("my long enough string")
      .position(CGPoint(x: 0, y: 100))
}

The result is I can only see "ugh string".

inokey
  • 5,434
  • 4
  • 21
  • 33

6 Answers6

9

.position(x, y) will position the center of the view to the specified coordinate with the parent.

You will need to use a Stacks/Container to position the displayed elements relative to each other using aligments and spacer.

Views always start out at the center of the screen.

Something like this:

   HStack(alignment: .top) {
        VStack(alignment: .leading) {
            Text("top left")
            Spacer()
            Text("bottom left")
        }

        Spacer()
        VStack(alignment: .leading) {
            Text("top right")
            Spacer()
            Text("bottom right")
        }
    }
Cjay
  • 1,093
  • 6
  • 11
2

You can use 'padding' instead of position.

Text("Hello World").padding(EdgeInsets.init(top: 100, leading: 0, bottom: 0, trailing: 0))
Markicevic
  • 1,025
  • 9
  • 20
2

According to the documentation of the function position(x:y:):

  • x: The x-coordinate at which to place the center of this view.
  • y: The y-coordinate at which to place the center of this view.

This will fix the center of your text at center of the superview.

You can also use the padding() function:

Text("my long enough string").padding(.top, 20)
Ky -
  • 30,724
  • 51
  • 192
  • 308
Rohit Makwana
  • 4,337
  • 1
  • 21
  • 29
1

The coordinate space on iOS has 0, 0 in the top-left corner. Your text is being truncated because the position attribute: “Fixes the center of this view at the specified point in its parent’s coordinate space.”

marcprux
  • 9,845
  • 3
  • 55
  • 72
0

You can also use the .offset modifier to offset the view with respect to the top left corner. If you use it just be aware that the effects can be drastically different based on the ordering of the modifiers.

Helam
  • 1,385
  • 13
  • 17
0

Fixes the center of this view at the specified point in its parent’s coordinate space.

guoliang li
  • 91
  • 1
  • 3