简体   繁体   中英

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:

Xcode 预览

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM