How To Position View Related To Parent In SwiftUI

SwiftUI tries by default position view in the best possible way. However, sometimes you want to do it on your own or you want to make some magic and position views related to parents ignoring SwiftUI behavior.

Let’s create a simple blue rectangle.

var body: some View {
    
Rectangle()
    
    .foregroundColor(.blue)
    
    .frame(width: 300, height: 300)
}

By default, it’s in the center of the view.

There is .position view modifier to put its center on specific X, Y place related to the parent view.

var body: some View {
    
Rectangle()
    
    .foregroundColor(.blue)
    
    .frame(width: 300, height: 300)
    
    .position(CGPoint(x: 0, y: 0))
}

Now, the rectangle’s center x is 0 and y is 0, but, if you click on the preview on the rectangle you notice that it’s not related to the whole screen but something else. It’s a safe area. And you want to ignore safe area use .ignoresSafeArea view modifier.

var body: some View {
    Rectangle()
    
    .foregroundColor(.blue)
    
    .frame(width: 300, height: 300)
    
    .position(CGPoint(x: 0, y: 0))
    
    .ignoresSafeArea()
}

If you embed a rectangle in VStack with some frame and background color it has the same effect. For example, you can move it to the right bottom edge.

var body: some View {
    
VStack {
    
    Rectangle()
    
        .foregroundColor(.blue)
    
        .frame(width: 100, height: 100)
    
        .position(CGPoint(x: 250, y: 250))
    }
    .
frame(width: 300, height: 300)
    .
background(Color.green)
}