Home > AI > IOS > SwiftUI >

position(x:y:)

Example:

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .frame(minWidth: 0, maxWidth: .infinity)
            .frame(height: 50)
            .background(Color.red)
            .position(x: UIScreen.main.bounds.width/2,
                      y: UIScreen.main.bounds.height - 45)
    }
}

This code has some problems:

  1. the position y is not same as the frame height of the text since if same, there is a bottom padding below the text. Do you know why?

There are safe areas at top, leading, bottom, and trailing of the screen. This is caused by the safe area. After ignoring safe areas, the offset value should be half of the Text height.

Text("Hello, world!")
    .frame(minWidth: 0, maxWidth: .infinity)
    .frame(height: 50)
    .background(Color.red)
    .position(x: UIScreen.main.bounds.width/2,
              y: UIScreen.main.bounds.height - 25)
    .edgesIgnoringSafeArea(.all)
  1. using position singly cannot promise the view is absolute located. If you try to wrap with VStack, the position of Text would get changed. Do you know how to get real absolute position?

Use ZStack

ZStack {

            Text("gooos")

            
            Text("Hello, world!")
                .frame(minWidth: 0, maxWidth: .infinity)
                .frame(height: 50)
                .background(Color.red)
                .position(x: UIScreen.main.bounds.width/2,
                          y: UIScreen.main.bounds.height - 25)
                .edgesIgnoringSafeArea(.all)

        }

Attention point:

The background modifier needs to precede position or entile parent view will get rendered.

Leave a Reply