Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HStack with SF Symbols Image not aligned centered

I have this simple SwiftUI code. I want all symbols to be aligned centered, just like the cloud symbol.

struct ContentView : View {
var body: some View {
    HStack(alignment: .center, spacing: 10.0) {
        Image(systemName: "cloud.sun")
        Image(systemName: "cloud")
        Image(systemName: "cloud.bolt")
        Text("Text")
        }.font(.title)
    }
}

But as you can see below, the first and the last symbol are not centered. Am I missing something, or is this a bug?

Centered HStack

Cheers!

like image 973
Daniel Avatar asked Jun 13 '19 10:06

Daniel


1 Answers

This is what it's going on.

enter image description here

The Image views are not resizing.

It looks like they're not aware of their intrinsic content size, or maybe it reports the wrong value.

To fix it:

struct ContentView : View {
    var body: some View {
        HStack(alignment: .center, spacing: 10.0) {
            Image(systemName: "cloud.sun")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .background(Color.red)
            Image(systemName: "cloud")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .background(Color.yellow)
            Image(systemName: "cloud.bolt")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .background(Color.pink)
            Text("Text").background(Color.green)
        }
        .frame(width: 250, height: 50)
        .background(Color.gray)
        .font(.title)

    }
}

...make the Images resizable, and also make sure the aspect ratio is set to .fit, or they will stretch.

Set also frame on the HStack or it will expand to fill the whole screen.

@MartinR suggested an even better solution - creating the images via UIImage - see his comment below.

struct ContentView : View {

    var body: some View {
        HStack {
            Image(uiImage: UIImage(systemName: "cloud.sun")!)
                .background(Color.red)
            Image(uiImage: UIImage(systemName: "cloud")!)
                .background(Color.yellow)
            Image(uiImage: UIImage(systemName: "cloud.bolt")!)
                .background(Color.pink)
            Text("Text").background(Color.green)
        }
        .background(Color.gray)
        .font(.title)

    }

}

Output:

enter image description here

like image 116
Matteo Pacini Avatar answered Nov 02 '22 15:11

Matteo Pacini