HStack with SF Symbols Image not aligned centered

2020-06-22 04:39发布

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!

1条回答
Lonely孤独者°
2楼-- · 2020-06-22 05:15

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

查看更多
登录 后发表回答