-1

enter image description here

Started learning SwiftUI, I want to remove this highlighted space between navigation title and Text inside VStack.

Sumit Jangra
  • 651
  • 5
  • 16
  • 1
    It would be best if you could go through the basics of SwiftUI to understand how SwiftUI layout works. Parent view offers some available space to child view (Text), it is up to the child view (Text) to decide how much space it needs. Text space takes up only the necessary space to accommodate the string it displays and centers it. `VStack { Text("aaa") Spacer() }` should fix it – user1046037 Nov 04 '22 at 11:13

1 Answers1

0

If you were to remove the NavigationView and had your VStack as the top-level view in your body, you'd see much the same layout.

That's because its frame is smaller than the frame available for it (in this case, most of the screen) and by default the smaller internal view gets centered both horizontally and vertically.

To move the text to the top of the screen, you need to ensure that your view will grow in size. The easiest way will be add to add a Spacer to the bottom of the VStack:

VStack(alignment: ...) {
  Text("...")
  Text("...")
  Spacer()
}

Another approach would be to wrap your VStack in a scroll view. This view will automatically expand itself to fill the height, and layout its subviews (your VStack) from the top downwards:

ScrollView {
  VStack(alignment: ...) {
    Text("...")
    Text("...")
  }
}

Each approach has upsides and downsides depending on how much other data you expect to also be in the view.

You could also manually adjust the frame of your VStack using the .frame() modifier:

VStack(alignment: ...) {
  Text("...")
  Text("...")
}
.frame(maxHeight: .infinity, alignment: .top)

This would give you much the same effect as using the spacer. But the spacer version is a better way to go, especially if you're only starting out with SwiftUI layout.

ScottM
  • 7,108
  • 1
  • 25
  • 42