iosswiftswiftuiswiftui-spacer

How to specifically position views in SwiftUI?


I am trying to position views in my iOS app using SwiftUI. While I know that I can use .position() to set a specific position on the screen, I have currently used a combination of VStack/HStack and Spacer() to position the element views. For example if I want some text to be displayed at the bottom right of the screen:

VStack{
    Spacer()
    HStack{
        Spacer()
        Text("Hello World!")
     }
 }

I am doing this for several element views, and I have realised that this may not be a good practice as it overlaps a lot of Spacers(). The reason I did not use .position() is because I would have to use GeometryReader for every element view. I would appreciate if anyone could clarify if using Spacers is the better approach or is there a better alternative?


Solution

  • Using Spacer is fine. However, it's worth remembering that an HStack and a VStack add some default spacing between their items. When there is only a small amount of space available, the spacing can sometimes have an impact on the layout. So you may want to eliminate the inter-view spacing by using VStack(spacing: 0) and HStack(spacing: 0).

    As far as simpler alternatives are concerned, the same effect can be achieved with less code by setting a .frame with alignment:

    var body: some View {
        Text("Hello World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
    }