Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading