How do I make an Image in Swift the same height as the text next to it?

Solution 1:

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

Solution 2:

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