[英]How do I make an Image in Swift the same height as the text next to it?
I'm brand new to Swift and am making an iOS Minesweeper app.我是 Swift 的新手,正在制作 iOS 扫雷应用程序。 At the top of the screen I want to have an image of a bomb next to a Text() object displaying the number of bombs remaining.在屏幕顶部,我想在 Text() object 旁边显示炸弹的图像,显示剩余的炸弹数量。
I'd like to have the image and/or HStack resize to whatever the height of the adjacent text is without having to hard-code it's dimensions.我想让图像和/或 HStack 调整到相邻文本的高度,而不必对其尺寸进行硬编码。
Can/how this be achieved?可以/如何实现?
The code so far looks like this:到目前为止的代码如下所示:
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)
@State var labelHeight = CGFloat.zero
HStack(alignment: .center, spacing: 10) {
Image("top_bomb")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxHeight: labelHeight)
Text(String(game.bombsRemaining))
.font(.system(size: 30, weight: .bold, design: .monospaced))
.overlay(
GeometryReader(content: { geometry in
Color.clear
.onAppear(perform: {
self.labelHeight = geometry.frame(in: .local).size.height
})
})
)
}
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height * 0.2, alignment: .trailing)
You just need to fix it by size, like你只需要按大小修复它,比如
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) // << !!
Note: also pay attention that you don't need to hardcode frame to screen size注意:还请注意,您不需要将帧硬编码为屏幕大小
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.