Home > Blockchain >  Constrain the size of an HStack (with Images) to the width of the device
Constrain the size of an HStack (with Images) to the width of the device

Time:11-26

I'm trying to make an iOS-app with SwiftUI.

Here's my code so far:

struct ContentView: View {
    var body: some View {
        VStack {
            Spacer()
            Text("SwiftUI Slots!")
            Spacer()
            HStack {
                Text("Credits: 1025")
            }
            Spacer()
            HStack {
                Image("apple")
                Image("cherry")
                Image("star")
            }
            Spacer()
            Button(action: {
                print("Testing 124")
            }, label: {
                Text("Spin")
            })
            Spacer()
                .scaledToFit()
        }
    }
}

The HStack with the three images in it causes trouble:

Xcode Preview

How can I constrain the size of the HStack to the size of the device, so that it doesn't overlap the edges?

CodePudding user response:

Use resizable() and aspectRatio()modifier for Image.

HStack {
  Image("apple").resizable().aspectRatio(contentMode: .fit)
  Image("cherry").resizable().aspectRatio(contentMode: .fit)
  Image("star").resizable().aspectRatio(contentMode: .fit)
}

You can also use

Image("star").resizable().scaledToFit()
  • Related