Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI generates unwanted space around an Image

Tags:

swiftui

The following code produces a simple VStack with Text views that show no spacing in-between them (rows 1 & 2).

However, adding an image to the 3rd row (green) adds unwanted spacing above and below the entire row.

struct ContentView: View {
  var body: some View {
    VStack {
      HStack {
        Text("one thing")
      }.background(Color(.yellow))
      HStack {
        Text("nothing")
      }.background(Color(.red))
      HStack {
        Text("three")
        Image(systemName: "star")
          .resizable()
          .frame(width: 8, height: 8)
      }.background(Color(.green))
      HStack {
        Text("three things")
      }.background(Color(.red))
    }
  }
}

How can I avoid the additional unwanted space?

The space shows independent of image size (even with an image just a few pixels in dimension).

And, of course, I'd like to know why the space is generated.

Thanks for any help

Screenshot of above code:

Output:

like image 249
nine stones Avatar asked Mar 03 '23 00:03

nine stones


1 Answers

You may adjust the spacing of VStack:

var body: some View {
            VStack (spacing: 0) {
                 HStack {
                   Text("one thing")
                 }.background(Color(.yellow))
                 HStack {
                   Text("nothing")
                 }.background(Color(.red))
                 HStack {
                   Text("three")
                   Image(systemName: "star")
                     .resizable()
                     .frame(width: 8, height: 8)
                 }.background(Color(.green))
                 HStack {
                   Text("three things")
                 }.background(Color(.red))
               }
             }
like image 126
E.Coms Avatar answered May 14 '23 12:05

E.Coms