我是 Swift 的新手,正在制作 iOS Minesweeper 應用程式。在螢屏頂部,我想在 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)
它看起來像:

uj5u.com熱心網友回復:
@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)
uj5u.com熱心網友回復:
你只需要按大小修復它,比如
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) // << !!
注意:還請注意,您不需要將幀硬編碼為螢屏大小
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415468.html
標籤:
下一篇:Swift:添加負數
