带有 SF 符号的 HStack 图像未居中对齐 [英] HStack with SF Symbols Image not aligned centered

查看:25
本文介绍了带有 SF 符号的 HStack 图像未居中对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的 SwiftUI 代码.我希望所有符号都居中对齐,就像云符号一样.

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?

干杯!

推荐答案

这是怎么回事.

Image 视图未调整大小.

他们似乎不知道自己的内在内容大小,或者可能报告了错误的值.

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

修复它:

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)

    }
}

...使 Images 可调整大小,并确保将纵横比设置为 .fit,否则它们会拉伸.

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

同时在 HStack 上设置框架,否则它会扩展以填满整个屏幕.

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

@MartinR 提出了一个更好的解决方案 - 通过 UIImage 创建图像 - 请参阅下面的评论.

@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)

    }

}

输出:

这篇关于带有 SF 符号的 HStack 图像未居中对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆