如何在 Swift 中使图像与其旁边的文本高度相同?

lll*_*lll 3 ios swift swiftui

我是 Swift 的新手,正在制作一个 iOS 扫雷应用程序。在屏幕顶部,我希望在 Text() 对象旁边有一个炸弹图像,显示剩余炸弹的数量。

我想让图像和/或 HStack 调整大小到相邻文本的高度,而不必对其尺寸进行硬编码。

这可以/如何实现?

到目前为止的代码如下所示:

HStack(alignment: .center, spacing: 10) {
    Image("top_bomb")
        .resizable()
        .aspectRatio(contentMode: .fit)
    Text(String(game.bombsRemaining))
        .font(.system(size: 30, weight: .bold, design: .monospaced))
}
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.1, alignment: .trailing)
Run Code Online (Sandbox Code Playgroud)

它看起来像: 扫雷应用程序

Asp*_*eri 6

你只需要按大小来修复它,比如

HStack(alignment: .center, spacing: 10) {
    Image("top_bomb")
        .resizable()
        .aspectRatio(contentMode: .fit)
    Text(String(game.bombsRemaining))
        .font(.system(size: 30, weight: .bold, design: .monospaced))
}
.fixedSize()                                        // << here !!
.frame(maxWidth: .infinity, alignment: .trailing)   // << !!
Run Code Online (Sandbox Code Playgroud)

注意:还要注意,您不需要将框架硬编码到屏幕尺寸