1

I have a SwiftUI Image view that displays only an SF symbol:

GeometryReader { g in
    Image(systemName: "a.square")
        .font(.system(size: g.size.width))
    }
}

It renders like this:

Preview of Image view

I tried modifying the view with the .multilineTextAlignment(.center) modifier to center it, and that didn't do anything.

burnsi
  • 6,194
  • 13
  • 17
  • 27
Adam
  • 153
  • 1
  • 8

2 Answers2

2

You can try adding this command line for it:

.position(x: g.size.width / 2, y: g.size.width / 2)

The code you wrote looks like this:

GeometryReader { g in
   Image(systemName: "a.square")
       .font(.system(size: g.size.width))
       .position(x: g.size.width / 2, y: g.size.width / 2)
}

}

enter image description here

baohoang
  • 616
  • 1
  • 5
  • 13
0

Why not the declarative way?

VStack {
    Image(systemName: "a.square")
        .resizable()
        .aspectRatio(1.0, contentMode: .fit)
        .padding()
    Spacer()
}
vadian
  • 274,689
  • 30
  • 353
  • 361
  • When I tried your solution, my SF symbol was indeed centered, but there were some other adverse effects. The symbol no longer retained the correct sizing in my view implementations. The correct sizing was only achieved using the GeometryReader container. – Adam Feb 27 '23 at 13:45